<?php

namespace Tests\Feature;

use App\Models\Branch;
use App\Models\CorporateCompany;
use App\Models\CorporateEmployee;
use App\Models\CorporateEmployeeDocument;
use App\Models\Employee;
use App\Models\RenewalOpportunity;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class SystemQualityControlTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
    }

    public function test_web_login_policy_and_temporary_password_gate_are_enforced(): void
    {
        $user = User::where('email', 'typist@almadina.ae')->firstOrFail();
        $user->update(['allow_web_login' => false]);

        $this->post(route('login'), ['login' => $user->email, 'password' => 'Password123!'])
            ->assertSessionHasErrors('login');
        $this->assertGuest();

        $user->update(['allow_web_login' => true, 'must_change_password' => true]);
        $this->post(route('login'), ['login' => $user->email, 'password' => 'Password123!'])
            ->assertRedirect(route('app.profile'));
        $this->get(route('app.work_queue'))->assertRedirect(route('app.profile'));
        $this->get(route('app.profile'))->assertOk()->assertSee('Password change required');
    }

    public function test_employee_profiles_documents_and_access_screen_are_operational(): void
    {
        $owner = User::where('email', 'owner@almadina.ae')->firstOrFail();
        $branch = Branch::where('tenant_id', $owner->tenant_id)->firstOrFail();
        $employee = Employee::create([
            'tenant_id' => $owner->tenant_id,
            'branch_id' => $branch->id,
            'employee_code' => 'EMP-QC-001',
            'first_name' => 'Quality',
            'last_name' => 'Officer',
            'full_name' => 'Quality Officer',
            'email' => 'quality.officer@example.ae',
            'designation' => 'Compliance Officer',
            'status' => 'active',
        ]);

        $this->actingAs($owner)->get(route('app.employees.index'))
            ->assertOk()->assertSee(route('app.employees.show', $employee));
        $this->actingAs($owner)->get(route('app.employees.show', $employee))
            ->assertOk()->assertSee('Compliance document vault');
        $this->actingAs($owner)->get(route('app.employees.give_access', $employee))
            ->assertOk()->assertSee('Grant ERP Access');

        $this->actingAs($owner)->post(route('app.employees.documents.store', $employee), [
            'document_type' => 'residence_visa',
            'document_number' => 'VISA-QC-001',
            'issue_date' => today()->subYear()->format('Y-m-d'),
            'expiry_date' => today()->addDays(30)->format('Y-m-d'),
            'reminder_enabled' => 1,
        ])->assertSessionHasNoErrors();

        $this->assertDatabaseHas('employee_documents', [
            'tenant_id' => $owner->tenant_id,
            'employee_id' => $employee->id,
            'document_number' => 'VISA-QC-001',
            'reminder_enabled' => true,
        ]);
    }

    public function test_employee_and_corporate_forms_reject_foreign_tenant_master_ids(): void
    {
        $owner = User::where('email', 'owner@almadina.ae')->firstOrFail();
        $otherTenant = Tenant::create(['company_name' => 'Other Typing Center', 'slug' => 'other-qc-center', 'status' => 'active']);
        $otherBranch = Branch::create(['tenant_id' => $otherTenant->id, 'name' => 'Other Branch', 'code' => 'QC-OTHER', 'status' => 'active']);
        $otherCompany = CorporateCompany::create([
            'tenant_id' => $otherTenant->id,
            'company_code' => 'OTHER-COMPANY',
            'name_en' => 'Other Tenant LLC',
            'status' => 'active',
        ]);

        $this->actingAs($owner)->from(route('app.employees.create'))->post(route('app.employees.store'), [
            'first_name' => 'Cross Tenant',
            'branch_id' => $otherBranch->id,
        ])->assertRedirect(route('app.employees.create'))->assertSessionHasErrors('branch_id');

        $this->actingAs($owner)->from(route('app.corporate.employees.create'))->post(route('app.corporate.employees.store'), [
            'full_name' => 'Cross Tenant Corporate Employee',
            'company_id' => $otherCompany->id,
        ])->assertRedirect(route('app.corporate.employees.create'))->assertSessionHasErrors('company_id');
    }

    public function test_corporate_employee_document_can_be_promoted_to_renewal_workflow(): void
    {
        $owner = User::where('email', 'owner@almadina.ae')->firstOrFail();
        $company = CorporateCompany::create([
            'tenant_id' => $owner->tenant_id,
            'company_code' => 'QC-COMPANY',
            'name_en' => 'QC Corporate Client LLC',
            'status' => 'active',
        ]);
        $employee = CorporateEmployee::create([
            'tenant_id' => $owner->tenant_id,
            'company_id' => $company->id,
            'corporate_employee_code' => 'CEMP-QC-001',
            'full_name' => 'Renewal Test Employee',
            'status' => 'active',
        ]);
        $document = CorporateEmployeeDocument::create([
            'tenant_id' => $owner->tenant_id,
            'corporate_employee_id' => $employee->id,
            'document_type' => 'work_permit',
            'document_number' => 'WP-QC-001',
            'expiry_date' => today()->addDays(20),
        ]);

        $response = $this->actingAs($owner)->post(route('app.corporate.expiries.renewal', $document));
        $opportunity = RenewalOpportunity::where('tenant_id', $owner->tenant_id)
            ->where('source_type', 'corporate_employee_document')
            ->where('source_id', $document->id)
            ->firstOrFail();

        $response->assertRedirect(route('app.renewals.show', $opportunity));
        $this->actingAs($owner)->get(route('app.corporate.employees.show', $employee))
            ->assertOk()->assertSee('Immigration document vault')->assertSee('WP-QC-001');
    }
}
