<?php

namespace MintyPHP\Service\Access;

use MintyPHP\Repository\Access\RoleRepository;
use MintyPHP\Service\Directory\DirectorySettingsGateway;
use MintyPHP\Service\Settings\SettingServicesFactory;

class RoleService
{
    public function __construct(
        private readonly ?RoleRepository $roleRepository = null,
        private readonly ?DirectorySettingsGateway $settingsGateway = null
    ) {
    }

    public function list(): array
    {
        return $this->roleRepository()->list();
    }

    public function listActive(): array
    {
        return $this->roleRepository()->listActive();
    }

    public function listPaged(array $options): array
    {
        return $this->roleRepository()->listPaged($options);
    }

    public function findByUuid(string $uuid): ?array
    {
        return $this->roleRepository()->findByUuid($uuid);
    }

    public function findById(int $id): ?array
    {
        return $this->roleRepository()->find($id);
    }

    public function createFromAdmin(array $input, int $currentUserId = 0): array
    {
        $form = $this->sanitizeBase($input);
        $errors = $this->validateBase($form, 0);

        if ($errors) {
            return ['ok' => false, 'errors' => $errors, 'form' => $form];
        }

        $createdId = $this->roleRepository()->create([
            'description' => $form['description'],
            'code' => $form['code'] ?: null,
            'active' => $form['active'],
            'created_by' => $currentUserId > 0 ? $currentUserId : null,
        ]);

        if (!$createdId) {
            return ['ok' => false, 'errors' => [t('Role can not be created')], 'form' => $form];
        }

        $createdRole = $this->roleRepository()->find((int) $createdId);
        $uuid = $createdRole['uuid'] ?? null;
        if (!empty($input['is_default'])) {
            $this->settingsGateway()->setDefaultRoleId((int) $createdId);
        }
        return ['ok' => true, 'form' => $form, 'uuid' => $uuid, 'id' => (int) $createdId];
    }

    public function updateFromAdmin(int $roleId, array $input, int $currentUserId = 0): array
    {
        $form = $this->sanitizeBase($input);
        $errors = $this->validateBase($form, $roleId);

        if ($errors) {
            return ['ok' => false, 'errors' => $errors, 'form' => $form];
        }

        $updated = $this->roleRepository()->update($roleId, [
            'description' => $form['description'],
            'code' => $form['code'] ?: null,
            'active' => $form['active'],
            'modified_by' => $currentUserId > 0 ? $currentUserId : null,
        ]);

        if (!$updated) {
            return ['ok' => false, 'errors' => [t('Role can not be updated')], 'form' => $form];
        }

        return ['ok' => true, 'form' => $form];
    }

    public function deleteByUuid(string $uuid): array
    {
        $uuid = trim($uuid);
        if ($uuid === '') {
            return ['ok' => false, 'status' => 404, 'error' => 'not_found'];
        }

        $role = $this->roleRepository()->findByUuid($uuid);
        if (!$role || !isset($role['id'])) {
            return ['ok' => false, 'status' => 404, 'error' => 'not_found'];
        }

        if (($role['description'] ?? '') === 'Admin') {
            return ['ok' => false, 'status' => 403, 'error' => 'admin_role_protected'];
        }

        $deleted = $this->roleRepository()->delete((int) $role['id']);
        if (!$deleted) {
            return ['ok' => false, 'status' => 500, 'error' => 'delete_failed'];
        }

        return ['ok' => true, 'role' => $role];
    }

    private function sanitizeBase(array $input): array
    {
        return [
            'description' => trim((string) ($input['description'] ?? '')),
            'code' => trim((string) ($input['code'] ?? '')),
            'active' => $this->normalizeActive($input['active'] ?? 1),
        ];
    }

    private function validateBase(array $form, int $excludeId): array
    {
        $errors = [];
        if ($form['description'] === '') {
            $errors[] = t('Description cannot be empty');
        }
        $code = $form['code'] ?? '';
        if ($code !== '' && $this->roleRepository()->existsByCode($code, $excludeId)) {
            $errors[] = t('Role code already exists');
        }
        return $errors;
    }

    private function normalizeActive($value): int
    {
        $value = strtolower(trim((string) $value));
        if (in_array($value, ['0', 'false', 'inactive'], true)) {
            return 0;
        }
        return 1;
    }

    private function roleRepository(): RoleRepository
    {
        return $this->roleRepository ?? new RoleRepository();
    }

    private function settingsGateway(): DirectorySettingsGateway
    {
        if ($this->settingsGateway instanceof DirectorySettingsGateway) {
            return $this->settingsGateway;
        }

        return new DirectorySettingsGateway(
            (new SettingServicesFactory())->createSettingGateway()
        );
    }
}
