<?php

namespace App\Http\Controllers\Api;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\PatrollingLocation\StorePatrollingLocationRequest;
use App\Http\Requests\PatrollingLocation\UpdatePatrollingLocationRequest;
use App\Http\Resources\PatrollingLocationResource;
use App\Models\PatrollingLocation;
use Illuminate\Support\Str;
use Spatie\QueryBuilder\QueryBuilder;

class PatrollingLocationController extends Controller
{
    public function index() {
        $query = QueryBuilder::for(PatrollingLocation::class)
            ->allowedFilters(['name', 'type', 'location_code', 'is_active', 'wing_id'])
            ->allowedIncludes(['wing'])
            ->latest();

        $locations = $query
            ->paginate(request("perPage", 15));

        return ApiResponse::paginated($locations);
    }

    public function store(StorePatrollingLocationRequest $request) {
        $location = new PatrollingLocation($request->validated());
        $location->location_code = $this->generateLocationCode();
        $location->save();

        return ApiResponse::created(
            new PatrollingLocationResource($location->load(['wing'])),
            "Patrolling location has been created successfully!"
        );
    }

    public function show(PatrollingLocation $patrollingLocation) {
        return ApiResponse::resource(
            new PatrollingLocationResource($patrollingLocation->load(['wing']))
        );
    }

    public function update(UpdatePatrollingLocationRequest $request, PatrollingLocation $patrollingLocation) {
        $patrollingLocation->update($request->validated());

        return ApiResponse::updated(
            new PatrollingLocationResource($patrollingLocation->load(['wing'])),
            "Patrolling location has been updated successfully!"
        );
    }

    public function destroy(PatrollingLocation $patrollingLocation) {
        $patrollingLocation->delete();

        return ApiResponse::deleted("Patrolling location has been deleted successfully!");
    }

    private function generateLocationCode(): string {
        do {
            $code = 'LOC' . strtoupper(Str::random(8));
        } while (PatrollingLocation::where('location_code', $code)->exists());

        return $code;
    }
}
