<?php

namespace MintyPHP\Service\Settings;

use MintyPHP\Repository\Access\RoleRepositoryInterface;
use MintyPHP\Repository\Org\DepartmentRepositoryInterface;
use MintyPHP\Repository\Tenant\TenantRepositoryInterface;

class SettingsDefaultsGateway
{
    public function __construct(
        private readonly SettingsMetadataGateway $settingsMetadataGateway,
        private readonly TenantRepositoryInterface $tenantRepository,
        private readonly RoleRepositoryInterface $roleRepository,
        private readonly DepartmentRepositoryInterface $departmentRepository
    ) {
    }

    public function getDefaultTenantId(): ?int
    {
        $id = $this->settingsMetadataGateway->getInt(SettingKeys::DEFAULT_TENANT_KEY);
        return $id && $id > 0 ? $id : null;
    }

    public function setDefaultTenantId(?int $tenantId, ?string $description = null): bool
    {
        $value = $tenantId && $tenantId > 0 ? (string) $tenantId : null;
        if ($value !== null) {
            $exists = $this->tenantRepository->find($tenantId);
            if (!$exists) {
                return false;
            }
        }

        $desc = $description ?? 'setting.default_tenant';
        return $this->settingsMetadataGateway->set(SettingKeys::DEFAULT_TENANT_KEY, $value, $desc);
    }

    public function getDefaultRoleId(): ?int
    {
        $id = $this->settingsMetadataGateway->getInt(SettingKeys::DEFAULT_ROLE_KEY);
        return $id && $id > 0 ? $id : null;
    }

    public function setDefaultRoleId(?int $roleId, ?string $description = null): bool
    {
        $value = $roleId && $roleId > 0 ? (string) $roleId : null;
        if ($value !== null) {
            $exists = $this->roleRepository->find($roleId);
            if (!$exists) {
                return false;
            }
        }

        $desc = $description ?? 'setting.default_role';
        return $this->settingsMetadataGateway->set(SettingKeys::DEFAULT_ROLE_KEY, $value, $desc);
    }

    public function getDefaultDepartmentId(): ?int
    {
        $id = $this->settingsMetadataGateway->getInt(SettingKeys::DEFAULT_DEPARTMENT_KEY);
        return $id && $id > 0 ? $id : null;
    }

    public function setDefaultDepartmentId(?int $departmentId, ?string $description = null): bool
    {
        $value = $departmentId && $departmentId > 0 ? (string) $departmentId : null;
        if ($value !== null) {
            $exists = $this->departmentRepository->find($departmentId);
            if (!$exists) {
                return false;
            }
        }

        $desc = $description ?? 'setting.default_department';
        return $this->settingsMetadataGateway->set(SettingKeys::DEFAULT_DEPARTMENT_KEY, $value, $desc);
    }
}
