<?php

namespace App\Http\Controllers\Api\Attendance;

use App\Http\Controllers\Controller;
use App\Services\AttendanceCommentTemplateService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AttendanceCommentTemplateController extends Controller
{
    public function __construct(
        protected AttendanceCommentTemplateService $service
    ) {
    }

    public function index(Request $request): JsonResponse
    {
        $activeOnly = filter_var(
            $request->query('active_only'),
            FILTER_VALIDATE_BOOL
        ) === true;

        return response()->json([
            'status' => 'success',
            'data' => $this->service->list($activeOnly),
        ]);
    }

    public function listData(Request $request): JsonResponse
    {
        $activeOnly = filter_var(
            $request->query('active_only'),
            FILTER_VALIDATE_BOOL
        ) === true;

        return response()->json([
            'templates' => $this->service->list($activeOnly),
        ]);
    }

    public function show(int $id): JsonResponse
    {
        return response()->json([
            'status' => 'success',
            'data' => $this->service->findOrFail($id),
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'min_score' => ['required', 'integer', 'min:0', 'max:100'],
            'max_score' => ['required', 'integer', 'min:0', 'max:100', 'gte:min_score'],
            'template_text' => ['required', 'string', 'max:5000'],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $data = $validator->validated();
        if (!array_key_exists('is_active', $data)) {
            $data['is_active'] = true;
        }

        $created = $this->service->create($data);

        return response()->json([
            'status' => 'success',
            'message' => 'Template created successfully.',
            'data' => $created,
        ], 201);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'min_score' => ['sometimes', 'integer', 'min:0', 'max:100'],
            'max_score' => ['sometimes', 'integer', 'min:0', 'max:100'],
            'template_text' => ['sometimes', 'string', 'max:5000'],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        $validator->after(function ($validator) use ($request) {
            $min = $request->has('min_score') ? (int) $request->input('min_score') : null;
            $max = $request->has('max_score') ? (int) $request->input('max_score') : null;
            if ($min !== null && $max !== null && $max < $min) {
                $validator->errors()->add('max_score', 'The max_score field must be greater than or equal to min_score.');
            }
        });

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $updated = $this->service->update($id, $validator->validated());

        return response()->json([
            'status' => 'success',
            'data' => $updated,
        ]);
    }

    public function destroy(int $id): JsonResponse
    {
        $this->service->delete($id);

        return response()->json([
            'status' => 'success',
            'message' => 'Template deleted successfully.',
        ]);
    }
}
