<?php

namespace App\Http\Controllers\Api\Attendance;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Attendance\LateSlipLogIndexRequest;
use App\Http\Resources\Attendance\LateSlipLogCollection;
use App\Http\Resources\Attendance\LateSlipLogResource;
use App\Models\LateSlipLog;
use App\Services\Attendance\LateSlipLogCommandService;
use App\Services\Attendance\LateSlipLogQueryService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class LateSlipLogsController extends BaseApiController
{
    public function __construct(
        private LateSlipLogQueryService $queryService,
        private LateSlipLogCommandService $commandService
    ) {
        parent::__construct();
    }

    public function index(LateSlipLogIndexRequest $request): JsonResponse
    {
        $this->authorize('viewAny', LateSlipLog::class);

        $filters = $request->validated();
        $page = (int) ($filters['page'] ?? 1);
        $perPage = (int) ($filters['per_page'] ?? 50);

        $logs = $this->queryService->paginate($filters, $page, $perPage);
        $collection = new LateSlipLogCollection($logs);

        return $this->success([
            'logs' => $collection->toArray($request),
            'meta' => $collection->with($request)['meta'],
        ]);
    }

    public function show(int $id): JsonResponse
    {
        $log = $this->queryService->find($id);
        if (!$log) {
            return $this->error('Late slip log not found.', Response::HTTP_NOT_FOUND);
        }

        $this->authorize('view', $log);

        return $this->success([
            'log' => new LateSlipLogResource($log),
        ]);
    }

    public function destroy(int $id): JsonResponse
    {
        $log = $this->queryService->find($id);
        if (!$log) {
            return $this->error('Late slip log not found.', Response::HTTP_NOT_FOUND);
        }

        $this->authorize('delete', $log);

        try {
            $deleted = $this->commandService->delete($log);
        } catch (\Throwable $e) {
            Log::error('Late slip log delete failed: ' . $e->getMessage());
            return $this->error('Unable to delete late slip log.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        if (!$deleted) {
            return $this->error('Unable to delete late slip log.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success(null, 'Late slip log deleted.');
    }
}
