<?php

namespace MintyPHP\Tests\Architecture;

use PHPUnit\Framework\TestCase;

class AuthzApiContractTest extends TestCase
{
    use ProjectFileAssertionSupport;

    public function testApiLoginIsBootstrappedAsPublic(): void
    {
        $content = $this->readProjectFile('pages/api/v1/auth/login().php');
        $this->assertStringContainsString('ApiBootstrap::init(false);', $content);
    }


    public function testApiBootstrapSupportsOptionalAuthRequirement(): void
    {
        $content = $this->readProjectFile('lib/Http/ApiBootstrap.php');
        $this->assertStringContainsString('public static function init(bool $requireAuth = true): void', $content);
        $this->assertStringContainsString('if ($requireAuth) {', $content);
        $this->assertStringContainsString('$authenticated = ApiAuth::authenticate();', $content);
        $this->assertStringContainsString('ApiResponse::unauthorized();', $content);
    }


    public function testApiUsersEndpointsUseCentralUserPolicy(): void
    {
        $indexContent = $this->readProjectFile('pages/api/v1/users/index().php');
        $this->assertStringContainsString('AuthorizationService::class', $indexContent);
        $this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_INDEX_GET', $indexContent);
        $this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_INDEX_POST', $indexContent);

        $showContent = $this->readProjectFile('pages/api/v1/users/show($id).php');
        $this->assertStringContainsString('AuthorizationService::class', $showContent);
        $this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_GET', $showContent);
        $this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_UPDATE', $showContent);
        $this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_DELETE', $showContent);
    }


    public function testApiPermissionAndSettingsEndpointsHaveExpectedGuards(): void
    {
        $permissionContent = $this->readProjectFile('pages/api/v1/permissions/index().php');
        $this->assertStringContainsString('ApiResponse::requireAbility(\\MintyPHP\\Service\\Access\\OperationsAuthorizationPolicy::ABILITY_API_PERMISSIONS_VIEW);', $permissionContent);
        $this->assertStringContainsString("foreach ((\$result['rows'] ?? []) as \$row)", $permissionContent);

        $settingsContent = $this->readProjectFile('pages/api/v1/settings/index().php');
        $this->assertStringContainsString('ApiResponse::requireAbility(\\MintyPHP\\Service\\Access\\OperationsAuthorizationPolicy::ABILITY_API_SETTINGS_VIEW);', $settingsContent);
        $this->assertStringContainsString('ApiResponse::requireAbility(\\MintyPHP\\Service\\Access\\OperationsAuthorizationPolicy::ABILITY_API_SETTINGS_UPDATE);', $settingsContent);
    }


    public function testApiMeEndpointsUseSelfServicePermissions(): void
    {
        $meContent = $this->readProjectFile('pages/api/v1/me/index().php');
        $this->assertStringContainsString('$method === \'PUT\' || $method === \'PATCH\'', $meContent);
        $this->assertStringContainsString('OperationsAuthorizationPolicy::ABILITY_API_ME_SELF_UPDATE', $meContent);
        $this->assertStringContainsString('ApiResponse::validationFromFormErrors(', $meContent);

        $passwordContent = $this->readProjectFile('pages/api/v1/me/password().php');
        $this->assertStringContainsString("ApiResponse::requireMethod('POST');", $passwordContent);
        $this->assertStringContainsString('ApiResponse::requireAbility(\\MintyPHP\\Service\\Access\\OperationsAuthorizationPolicy::ABILITY_API_ME_SELF_UPDATE);', $passwordContent);

        $avatarContent = $this->readProjectFile('pages/api/v1/me/avatar().php');
        $this->assertStringContainsString("define('MINTY_ALLOW_OUTPUT', true);", $avatarContent);
        $this->assertStringContainsString('OperationsAuthorizationPolicy::ABILITY_API_ME_SELF_UPDATE', $avatarContent);
    }


    public function testApiAvatarEndpointsUseExpectedAuthorizationModel(): void
    {
        $userAvatarContent = $this->readProjectFile('pages/api/v1/users/avatar($id).php');
        $this->assertStringContainsString('UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_GET', $userAvatarContent);

        $tenantAvatarContent = $this->readProjectFile('pages/api/v1/tenants/avatar($id).php');
        $this->assertStringContainsString('OperationsAuthorizationPolicy::ABILITY_API_TENANTS_VIEW', $tenantAvatarContent);
        $this->assertStringContainsString("ApiAuth::requireResourceAccess('tenants', \$tenantId);", $tenantAvatarContent);
    }


    public function testApiTenantShowExposesFullTenantMasterData(): void
    {
        $tenantShowContent = $this->readProjectFile('pages/api/v1/tenants/show($id).php');
        $this->assertStringContainsString("'region' => \$tenant['region'] ?? ''", $tenantShowContent);
        $this->assertStringContainsString("'vat_id' => \$tenant['vat_id'] ?? ''", $tenantShowContent);
        $this->assertStringContainsString("'support_email' => \$tenant['support_email'] ?? ''", $tenantShowContent);
        $this->assertStringContainsString("'billing_email' => \$tenant['billing_email'] ?? ''", $tenantShowContent);
        $this->assertStringContainsString("'primary_color_use_default' => \$primaryColor === ''", $tenantShowContent);
        $this->assertStringContainsString("'allow_user_theme_mode' => \$allowUserThemeMode", $tenantShowContent);

        $openApiContent = $this->readProjectFile('docs/openapi.yaml');
        $this->assertStringContainsString('TenantShowResponse:', $openApiContent);
        $this->assertStringContainsString('primary_color_use_default:', $openApiContent);
        $this->assertStringContainsString('allow_user_theme_mode:', $openApiContent);
        $this->assertStringContainsString('support_email:', $openApiContent);
    }


    public function testApiUserWriteEndpointsUseUuidAssignmentInput(): void
    {
        $usersIndex = $this->readProjectFile('pages/api/v1/users/index().php');
        $this->assertStringContainsString('UserApiWriteInputMapper::class', $usersIndex);
        $this->assertStringContainsString('->normalize($input)', $usersIndex);

        $usersShow = $this->readProjectFile('pages/api/v1/users/show($id).php');
        $this->assertStringContainsString('UserApiWriteInputMapper::class', $usersShow);
        $this->assertStringContainsString('->normalize($input)', $usersShow);

        $mapper = $this->readProjectFile('lib/Service/User/UserApiWriteInputMapper.php');
        $this->assertStringContainsString("'tenant_ids' => 'use_tenant_uuids'", $mapper);
        $this->assertStringContainsString("'role_ids' => 'use_role_uuids'", $mapper);
        $this->assertStringContainsString("'department_ids' => 'use_department_uuids'", $mapper);
        $this->assertStringContainsString("'primary_tenant_id' => 'use_primary_tenant_uuid'", $mapper);
    }


    public function testApiDepartmentEndpointsUseTenantUuidAndNoTenantIdExposure(): void
    {
        $departmentIndex = $this->readProjectFile('pages/api/v1/departments/index().php');
        $this->assertStringContainsString("ApiResponse::validationFromFormErrors(formErrorsFrom(['tenant_id' => ['use_tenant_uuid']]));", $departmentIndex);
        $this->assertStringContainsString("if (array_key_exists('tenant_uuid', \$input)) {", $departmentIndex);

        $departmentShow = $this->readProjectFile('pages/api/v1/departments/show($id).php');
        $this->assertStringContainsString("'tenant_uuid' => \$tenantUuid", $departmentShow);
        $this->assertStringNotContainsString("'tenant_id' => \$department['tenant_id'] ?? null", $departmentShow);
        $this->assertStringContainsString("'cost_center' => \$department['cost_center'] ?? ''", $departmentShow);
    }


    public function testApiRoleShowIncludesPermissionKeys(): void
    {
        $roleShow = $this->readProjectFile('pages/api/v1/roles/show($id).php');
        $this->assertStringContainsString('RolePermissionRepository::class', $roleShow);
        $this->assertStringContainsString('listPermissionKeysByRoleIds([$roleId])', $roleShow);
        $this->assertStringContainsString("'permission_keys' => \$permissionKeys", $roleShow);
    }


    public function testOpenApiMarksLoginAsPublic(): void
    {
        $content = $this->readProjectFile('docs/openapi.yaml');
        $this->assertMatchesRegularExpression('/\/auth\/login:\s+post:.*?security:\s*\[\]/s', $content);
        $this->assertStringContainsString('no Authorization header required', $content);
    }


    public function testOpenApiIncludesNewCriticalFrontendEndpoints(): void
    {
        $content = $this->readProjectFile('docs/openapi.yaml');
        $this->assertStringContainsString('/permissions:', $content);
        $this->assertStringContainsString('/me/password:', $content);
        $this->assertStringContainsString('/me/avatar:', $content);
        $this->assertStringContainsString('/users/avatar/{uuid}:', $content);
        $this->assertStringContainsString('/tenants/avatar/{uuid}:', $content);
        $this->assertStringContainsString('/settings:', $content);
        $this->assertStringContainsString('/settings/public:', $content);
    }


    public function testOpenApiUsesUuidBasedMasterDataContracts(): void
    {
        $content = $this->readProjectFile('docs/openapi.yaml');
        $this->assertStringContainsString('required: [description, tenant_uuid]', $content);
        $this->assertStringContainsString('tenant_uuids:', $content);
        $this->assertStringContainsString('primary_tenant_uuid:', $content);
        $this->assertStringContainsString('role_uuids:', $content);
        $this->assertStringContainsString('department_uuids:', $content);
        $this->assertStringContainsString('permission_keys:', $content);
        $this->assertStringContainsString('tenant_uuid:', $content);
    }


    public function testApiErrorEnvelopeIsCentralizedAndRequestIdAware(): void
    {
        $apiResponse = $this->readProjectFile('lib/Http/ApiResponse.php');
        $this->assertStringContainsString("'ok' => false", $apiResponse);
        $this->assertStringContainsString("'error_code' => \$normalizedErrorCode", $apiResponse);
        $this->assertStringContainsString("'details' => \$normalizedDetails", $apiResponse);
        $this->assertStringContainsString("header('X-Request-Id: ' . \$requestId);", $apiResponse);
        $this->assertStringNotContainsString("'error' => \$normalizedErrorCode", $apiResponse);
        $this->assertStringNotContainsString("\$body['errors']", $apiResponse);

        $openApi = $this->readProjectFile('docs/openapi.yaml');
        $this->assertStringContainsString('required: [ok, request_id, error_code, details]', $openApi);
        $this->assertStringNotContainsString('Legacy alias of `error_code`', $openApi);
        $this->assertStringNotContainsString('Legacy alias of `details.errors`', $openApi);
    }


}
