<?php

namespace App\Http\Controllers\Api;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\PatrolRound\StorePatrolRoundRequest;
use App\Http\Requests\PatrolRound\UpdatePatrolRoundRequest;
use App\Http\Resources\PatrolRoundResource;
use App\Models\PatrolRound;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PatrolRoundController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = PatrolRound::query();

        // Filter by active status
        if ($request->has('is_active')) {
            $query->where('is_active', $request->boolean('is_active'));
        }

        $patrolRounds = $query->orderByTime()->get();

        return ApiResponse::success(
            PatrolRoundResource::collection($patrolRounds),
            'Patrol rounds retrieved successfully'
        );
    }

    public function store(StorePatrolRoundRequest $request): JsonResponse
    {
        $patrolRound = PatrolRound::create($request->validated());

        return ApiResponse::success(
            new PatrolRoundResource($patrolRound),
            'Patrol round created successfully',
            201
        );
    }

    public function show(PatrolRound $patrolRound): JsonResponse
    {
        return ApiResponse::success(
            new PatrolRoundResource($patrolRound),
            'Patrol round retrieved successfully'
        );
    }

    public function update(UpdatePatrolRoundRequest $request, PatrolRound $patrolRound): JsonResponse
    {
        $patrolRound->update($request->validated());

        return ApiResponse::success(
            new PatrolRoundResource($patrolRound),
            'Patrol round updated successfully'
        );
    }

    public function destroy(PatrolRound $patrolRound): JsonResponse
    {
        // Check if patrol round has associated daily patrol summaries
        if ($patrolRound->dailyPatrolSummaries()->exists()) {
            return ApiResponse::error(
                'Cannot delete patrol round that has associated patrol summaries',
                422
            );
        }

        $patrolRound->delete();

        return ApiResponse::success(
            null,
            'Patrol round deleted successfully'
        );
    }

    public function active(): JsonResponse
    {
        $activeRounds = PatrolRound::active()->orderByTime()->get();

        return ApiResponse::success(
            PatrolRoundResource::collection($activeRounds),
            'Active patrol rounds retrieved successfully'
        );
    }
}
