<?php

declare(strict_types=1);

namespace App\Application\Admin;

use App\Domain\Audit\AuditAction;
use App\Domain\Audit\AuditEmitter;
use App\Domain\Reputation\DecayFunction;
use App\Infrastructure\Category\CategoryRepository;
use Doctrine\DBAL\Connection;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Admin CRUD over `categories`. Slugs are kebab-case lowercase + unique;
 * decay function is `linear|exponential`; decay param is non-negative.
 *
 * Delete semantics (SPEC §M10.1):
 *  - if the category is referenced by `policy_category_thresholds` OR
 *    `reports`, refuse with 409 + a `usage` payload describing the
 *    references. Soft-delete via `is_active=false` is the recommended
 *    fallback (do that explicitly via PATCH).
 *  - if no references exist, hard-delete.
 *
 * RBAC: list/show ⇒ Viewer; create/update/delete ⇒ Admin.
 */
final class CategoriesController
{
    use AdminControllerSupport;

    private const SLUG_PATTERN = '/^[a-z][a-z0-9_]{0,63}$/';

    public function __construct(
        private readonly CategoryRepository $categories,
        private readonly AuditEmitter $audit,
        private readonly Connection $connection,
    ) {
    }

    public function list(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $items = array_map(static fn ($c) => $c->toArray(), $this->categories->listAll());

        return self::json($response, 200, [
            'items' => $items,
            'total' => count($items),
        ]);
    }

    /**
     * @param array{id: string} $args
     */
    public function show(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $id = self::parseId($args['id']);
        if ($id === null) {
            return self::error($response, 404, 'not_found');
        }
        $category = $this->categories->findById($id);
        if ($category === null) {
            return self::error($response, 404, 'not_found');
        }

        return self::json($response, 200, $category->toArray());
    }

    public function create(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $body = self::jsonBody($request);
        $errors = [];

        $slug = isset($body['slug']) && is_string($body['slug']) ? trim($body['slug']) : '';
        if ($slug === '' || preg_match(self::SLUG_PATTERN, $slug) !== 1) {
            $errors['slug'] = 'required, lowercase alpha + digits + underscore, ≤64 chars';
        } elseif ($this->categories->findBySlug($slug) !== null) {
            $errors['slug'] = 'already exists';
        }

        // SEC_REVIEW F52: strip C0/C1 control characters from free-form
        // input before it lands in `audit_log.target_label` /
        // `details_json`. Slug is already regex-validated.
        $name = self::cleanString($body['name'] ?? null) ?? '';
        if ($name === '' || strlen($name) > 128) {
            $errors['name'] = 'required, 1–128 chars';
        }

        $description = null;
        if (array_key_exists('description', $body)) {
            if ($body['description'] !== null && !is_string($body['description'])) {
                $errors['description'] = 'must be string or null';
            } else {
                $description = is_string($body['description'])
                    ? self::stripControlChars($body['description'])
                    : null;
            }
        }

        $decayFunction = null;
        $rawFn = $body['decay_function'] ?? null;
        if (is_string($rawFn)) {
            $decayFunction = DecayFunction::tryFrom($rawFn);
        }
        if ($decayFunction === null) {
            $errors['decay_function'] = 'required, "linear" or "exponential"';
        }

        $decayParam = null;
        if (isset($body['decay_param']) && (is_int($body['decay_param']) || is_float($body['decay_param']))) {
            $decayParam = (float) $body['decay_param'];
            if ($decayParam <= 0) {
                $errors['decay_param'] = 'must be positive';
            }
        } else {
            $errors['decay_param'] = 'required, positive number';
        }

        $isActive = true;
        if (array_key_exists('is_active', $body)) {
            if (!is_bool($body['is_active'])) {
                $errors['is_active'] = 'must be boolean';
            } else {
                $isActive = $body['is_active'];
            }
        }

        if ($errors !== []) {
            return self::validationFailed($response, $errors);
        }

        /** @var DecayFunction $decayFunction */
        /** @var float $decayParam */
        $auditCtx = self::auditContext($request);
        $id = $this->connection->transactional(function () use ($slug, $name, $description, $decayFunction, $decayParam, $isActive, $auditCtx): int {
            $id = $this->categories->create($slug, $name, $description, $decayFunction, $decayParam, $isActive);
            $this->audit->emitOrThrow(
                AuditAction::CATEGORY_CREATED,
                'category',
                $id,
                ['slug' => $slug, 'name' => $name, 'decay_function' => $decayFunction->value, 'decay_param' => $decayParam],
                $auditCtx,
                $slug,
            );

            return $id;
        });

        $created = $this->categories->findById($id);
        if ($created === null) {
            return self::error($response, 500, 'create_failed');
        }

        return self::json($response, 201, $created->toArray());
    }

    /**
     * @param array{id: string} $args
     */
    public function update(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $id = self::parseId($args['id']);
        if ($id === null) {
            return self::error($response, 404, 'not_found');
        }
        $existing = $this->categories->findById($id);
        if ($existing === null) {
            return self::error($response, 404, 'not_found');
        }

        $body = self::jsonBody($request);
        $errors = [];
        $fields = [];

        if (array_key_exists('slug', $body)) {
            if (!is_string($body['slug']) || preg_match(self::SLUG_PATTERN, trim($body['slug'])) !== 1) {
                $errors['slug'] = 'lowercase alpha + digits + underscore, ≤64 chars';
            } else {
                $newSlug = trim($body['slug']);
                $other = $this->categories->findBySlug($newSlug);
                if ($other !== null && $other->id !== $id) {
                    $errors['slug'] = 'already exists';
                } else {
                    $fields['slug'] = $newSlug;
                }
            }
        }

        if (array_key_exists('name', $body)) {
            // SEC_REVIEW F52: see create() — same strip applied on update.
            $cleaned = self::cleanString($body['name']);
            if ($cleaned === null || $cleaned === '' || strlen($cleaned) > 128) {
                $errors['name'] = 'required, 1–128 chars';
            } else {
                $fields['name'] = $cleaned;
            }
        }

        if (array_key_exists('description', $body)) {
            if ($body['description'] !== null && !is_string($body['description'])) {
                $errors['description'] = 'must be string or null';
            } else {
                $fields['description'] = is_string($body['description'])
                    ? self::stripControlChars($body['description'])
                    : null;
            }
        }

        if (array_key_exists('decay_function', $body)) {
            $fn = is_string($body['decay_function']) ? DecayFunction::tryFrom($body['decay_function']) : null;
            if ($fn === null) {
                $errors['decay_function'] = '"linear" or "exponential"';
            } else {
                $fields['decay_function'] = $fn->value;
            }
        }

        if (array_key_exists('decay_param', $body)) {
            if (is_int($body['decay_param']) || is_float($body['decay_param'])) {
                $value = (float) $body['decay_param'];
                if ($value <= 0) {
                    $errors['decay_param'] = 'must be positive';
                } else {
                    $fields['decay_param'] = number_format($value, 4, '.', '');
                }
            } else {
                $errors['decay_param'] = 'must be positive number';
            }
        }

        if (array_key_exists('is_active', $body)) {
            if (!is_bool($body['is_active'])) {
                $errors['is_active'] = 'must be boolean';
            } else {
                $fields['is_active'] = $body['is_active'] ? 1 : 0;
            }
        }

        if ($errors !== []) {
            return self::validationFailed($response, $errors);
        }

        $beforeSnapshot = [
            'slug' => $existing->slug,
            'name' => $existing->name,
            'description' => $existing->description,
            'decay_function' => $existing->decayFunction->value,
            'decay_param' => number_format($existing->decayParam, 4, '.', ''),
            'is_active' => $existing->isActive ? 1 : 0,
        ];

        $auditCtx = self::auditContext($request);
        $this->connection->transactional(function () use ($id, $fields, $existing, $beforeSnapshot, $auditCtx): void {
            $this->categories->update($id, $fields);
            $updatedSlug = isset($fields['slug']) ? (string) $fields['slug'] : $existing->slug;
            $this->audit->emitOrThrow(
                AuditAction::CATEGORY_UPDATED,
                'category',
                $id,
                ['slug' => $existing->slug, 'changes' => self::diffFields($beforeSnapshot, $fields)],
                $auditCtx,
                $updatedSlug,
            );
        });

        $updated = $this->categories->findById($id);
        if ($updated === null) {
            return self::error($response, 500, 'update_failed');
        }

        return self::json($response, 200, $updated->toArray());
    }

    /**
     * @param array{id: string} $args
     */
    public function delete(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $id = self::parseId($args['id']);
        if ($id === null) {
            return self::error($response, 404, 'not_found');
        }
        $existing = $this->categories->findById($id);
        if ($existing === null) {
            return self::error($response, 404, 'not_found');
        }

        $policyRefs = $this->categories->policyReferenceCount($id);
        $reportRefs = $this->categories->reportReferenceCount($id);
        if ($policyRefs > 0 || $reportRefs > 0) {
            return self::json($response, 409, [
                'error' => 'category_in_use',
                'usage' => [
                    'policies' => $policyRefs,
                    'reports' => $reportRefs,
                ],
                'hint' => 'PATCH with is_active=false to soft-delete instead.',
            ]);
        }

        $auditCtx = self::auditContext($request);
        $this->connection->transactional(function () use ($id, $existing, $auditCtx): void {
            $this->categories->delete($id);
            $this->audit->emitOrThrow(
                AuditAction::CATEGORY_DELETED,
                'category',
                $id,
                ['slug' => $existing->slug, 'name' => $existing->name],
                $auditCtx,
                $existing->slug,
            );
        });

        return $response->withStatus(204);
    }

    private static function parseId(string $raw): ?int
    {
        return preg_match('/^[1-9][0-9]*$/', $raw) === 1 ? (int) $raw : null;
    }
}
