<?php

namespace App\Filters;

use App\Exceptions\SchoolYear\SchoolYearWriteConflictException;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

final class SchoolYearWritableFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (! $request instanceof IncomingRequest) {
            return null;
        }

        try {
            service('schoolYearWriteGuard')->assertWritable(
                service('schoolYearContext')->resolve($request)
            );

            return null;
        } catch (SchoolYearWriteConflictException $e) {
            log_message('warning', 'Historical school-year write blocked: {message}', [
                'message' => $e->getMessage(),
            ]);

            if ($request->isAJAX() || str_contains(strtolower($request->getHeaderLine('Accept')), 'application/json')) {
                return service('response')
                    ->setStatusCode(409)
                    ->setJSON([
                        'status' => 409,
                        'error' => 'Read-only school year',
                        'message' => $e->getMessage(),
                    ]);
            }

            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        return null;
    }
}
