<?php

namespace App\Http\Controllers;

use App\Services\Api\ApiTokenService;
use App\Services\Api\ExternalIncidentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ApiController extends Controller
{
    private $tokenService;
    private $incidentService;

    public function __construct(ApiTokenService $tokenService, ExternalIncidentService $incidentService)
    {
        $this->tokenService = $tokenService;
        $this->incidentService = $incidentService;
    }

    public function gettoken(Request $request)
    {
        $validated = $request->validate([
            'username' => ['required', 'string', 'max:255'],
            'password' => ['required', 'string', 'max:255'],
        ]);

        $token = $this->tokenService->issue($validated['username'], $validated['password']);

        if (! $token) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid API credentials',
            ], 401);
        }

        return response()->json(array_merge(['success' => true], $token));
    }

    public function processdata(Request $request)
    {
        if (! $this->tokenService->isValid($request)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid or expired token',
            ], 401);
        }

        try {
            $validated = $request->validate([
                'case_number' => ['required', 'string', 'max:100'],
                'reporting_date' => ['required', 'date'],
                'district' => ['required', 'string', 'max:150'],
                'subcounty' => ['required', 'string', 'max:150'],
                'parish' => ['required', 'string', 'max:150'],
                'victim_gender' => ['required', 'string', 'max:20'],
                'victim_age' => ['required', 'numeric', 'min:0', 'max:130'],
                'incident_type' => ['required', 'string', 'max:150'],
                'incident_date' => ['required', 'date'],
                'incident_time' => ['required', 'string', 'max:100'],
                'case_status' => ['required', 'string', 'max:150'],
            ]);

            $result = $this->incidentService->process($validated);

            return response()->json([
                'success' => true,
                'message' => 'Incident data processed successfully',
                'data' => $result,
            ], 201);
        } catch (\Throwable $e) {
            Log::error('NGBVD API incident processing failed', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Incident data could not be processed. No partial records were committed.',
            ], 500);
        }
    }

    public function getIncidentValues(Request $request)
    {
        if (! $this->tokenService->isValid($request)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid or expired token',
            ], 401);
        }

        $validated = $request->validate([
            'startdate' => ['nullable', 'date'],
            'enddate' => ['nullable', 'date'],
            'district_id' => ['nullable'],
            'incident_id' => ['nullable'],
        ]);

        $startDate = $validated['startdate'] ?? date('Y-m-01');
        $endDate = $validated['enddate'] ?? date('Y-m-d');

        $payload = $this->incidentService->incidentValues($startDate, $endDate, [
            'district_id' => $validated['district_id'] ?? null,
            'incident_id' => $validated['incident_id'] ?? null,
        ]);

        return response()->json(array_merge([
            'success' => true,
            'message' => 'Incident statistics generated successfully.',
        ], $payload));
    }
}
