<?php

namespace Kylin\Guardian\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;
use Kylin\Guardian\Services\GuardianNotifyService;
use Kylin\Guardian\Services\GuardianService;

/**
 * 监护人控制器
 *
 * 提供监护人注册、绑定、解绑、通知等 API。
 */
class GuardianController extends BaseController
{
    public function __construct(
        private readonly GuardianService $guardianService,
        private readonly GuardianNotifyService $notifyService,
    ) {}

    /**
     * 监护人注册
     */
    public function register(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:50',
            'phone' => 'required|string|max:20',
            'id_card' => 'nullable|string|max:20',
            'relationship' => 'required|string|in:parent,grandparent,other_relative,legal_guardian',
        ]);

        $data['user_id'] = $request->user()->id;

        $guardian = $this->guardianService->register($data);

        return ApiResponse::created($guardian, '监护人注册成功');
    }

    /**
     * 绑定未成年人
     */
    public function bind(Request $request): JsonResponse
    {
        $data = $request->validate([
            'minor_user_id' => 'required|integer|exists:users,id',
            'relationship' => 'required|string|in:parent,grandparent,other_relative,legal_guardian',
        ]);

        $guardian = $this->guardianService->findGuardianByUserId($request->user()->id);

        $binding = $this->guardianService->bind(
            $guardian->id,
            $data['minor_user_id'],
            $data['relationship']
        );

        return ApiResponse::created($binding->load('minorUser'), '绑定成功');
    }

    /**
     * 解绑
     */
    public function unbind(Request $request, int $bindingId): JsonResponse
    {
        $this->authorizeBinding($request, $bindingId);

        $this->guardianService->unbind($bindingId);

        return ApiResponse::success(null, '解绑成功');
    }

    /**
     * 绑定列表
     */
    public function bindings(Request $request): JsonResponse
    {
        $guardian = $this->guardianService->findGuardianByUserId($request->user()->id);

        $bindings = $this->guardianService->getBindings($guardian->id);

        return ApiResponse::success($bindings);
    }

    /**
     * 未成年人游戏报告
     */
    public function report(Request $request, int $bindingId): JsonResponse
    {
        $this->authorizeBinding($request, $bindingId);

        $report = $this->guardianService->getMinorReport($bindingId);

        return ApiResponse::success($report);
    }

    /**
     * 设置时间限制
     */
    public function setPlayLimit(Request $request, int $bindingId): JsonResponse
    {
        $this->authorizeBinding($request, $bindingId);

        $limits = $request->validate([
            'daily_minutes' => 'sometimes|integer|min:0|max:480',
            'weekend_daily_minutes' => 'sometimes|integer|min:0|max:480',
            'allowed_periods' => 'sometimes|array',
            'allowed_periods.*.start' => 'required_with:allowed_periods|string',
            'allowed_periods.*.end' => 'required_with:allowed_periods|string',
        ]);

        $binding = $this->guardianService->setPlayLimit($bindingId, $limits);

        return ApiResponse::success($binding, '时间限制设置成功');
    }

    /**
     * 设置消费限制
     */
    public function setSpendingLimit(Request $request, int $bindingId): JsonResponse
    {
        $this->authorizeBinding($request, $bindingId);

        $limits = $request->validate([
            'daily_max' => 'sometimes|numeric|min:0',
            'monthly_max' => 'sometimes|numeric|min:0',
            'single_max' => 'sometimes|numeric|min:0',
        ]);

        $binding = $this->guardianService->setSpendingLimit($bindingId, $limits);

        return ApiResponse::success($binding, '消费限制设置成功');
    }

    /**
     * 强制下线
     */
    public function forceOffline(Request $request, int $bindingId): JsonResponse
    {
        $this->authorizeBinding($request, $bindingId);

        $this->guardianService->forceOffline($bindingId);
        $this->notifyService->notifyForceOffline($bindingId);

        return ApiResponse::success(null, '已强制下线');
    }

    /**
     * 允许上线
     */
    public function allowOnline(Request $request, int $bindingId): JsonResponse
    {
        $this->authorizeBinding($request, $bindingId);

        $this->guardianService->allowOnline($bindingId);

        return ApiResponse::success(null, '已允许上线');
    }

    /**
     * 获取远程配置
     */
    public function remoteConfig(Request $request, int $bindingId): JsonResponse
    {
        $this->authorizeBinding($request, $bindingId);

        $config = $this->guardianService->getRemoteConfig($bindingId);

        return ApiResponse::success($config);
    }

    /**
     * 校验当前用户是否有权操作指定绑定关系
     */
    private function authorizeBinding(Request $request, int $bindingId): void
    {
        $binding = $this->guardianService->findBinding($bindingId);
        $guardian = $this->guardianService->findGuardian($binding->guardian_id);

        if ($guardian->user_id !== $request->user()->id) {
            throw new \Kylin\Guardian\Exceptions\GuardianException(
                \Kylin\Guardian\Enums\GuardianErrorCode::Unauthorized
            );
        }
    }
}
