<?php

namespace Tests\Feature;

use App\Models\User;
use App\Models\EmployerProfile;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class EmployerProfileWebTest extends TestCase
{
    use RefreshDatabase;

    protected $employer;

    protected function setUp(): void
    {
        parent::setUp();

        $this->employer = User::create([
            'name' => 'Jane Sponsor',
            'email' => 'sponsor@example.com',
            'password' => bcrypt('password'),
            'role' => 'employer',
        ]);

        EmployerProfile::create([
            'user_id' => $this->employer->id,
            'company_name' => 'Sponsor Co',
            'phone' => '+971501112222',
            'verification_status' => 'pending',
            'language' => 'English',
            'notifications' => true,
        ]);
    }

    /**
     * Test displaying the employer profile update form.
     */
    public function test_employer_can_view_web_profile()
    {
        $response = $this->actingAs($this->employer)
            ->withSession(['user' => $this->employer])
            ->get('/employer/profile');

        $response->assertStatus(200);
    }

    /**
     * Test uploading Emirates ID from Web UI: extracts OCR details and purges files.
     */
    public function test_employer_upload_emirates_id_ocr_and_purge()
    {
        Storage::fake('local');

        $fakeFront = UploadedFile::fake()->create('emirates_id_front.jpg', 500, 'image/jpeg');
        $fakeBack = UploadedFile::fake()->create('emirates_id_back.jpg', 500, 'image/jpeg');

        $response = $this->actingAs($this->employer)
            ->withSession(['user' => $this->employer])
            ->post('/employer/profile/update', [
                'name' => 'Jane Sponsor Updated',
                'email' => 'sponsor@example.com',
                'phone' => '+971509999999',
                'company_name' => 'Sponsor Co Updated',
                'language' => 'English',
                'notifications' => true,
                'emirates_id_front' => $fakeFront,
                'emirates_id_back' => $fakeBack,
            ]);

        $response->assertRedirect();

        // 1. Verify physical files were deleted (purged)
        $files = Storage::disk('local')->allFiles('temp/employer');
        $this->assertEmpty($files, 'Emirates ID physical files were not purged.');

        // 2. Verify database records updated with placeholders and extracted details
        $profile = $this->employer->fresh()->employerProfile;
        $this->assertEquals('[DELETED_FOR_PDPL_COMPLIANCE]', $profile->emirates_id_front);
        $this->assertEquals('[DELETED_FOR_PDPL_COMPLIANCE]', $profile->emirates_id_back);
        $this->assertNotNull($profile->emirates_id_number);
        $this->assertNotNull($profile->emirates_id_expiry);
        $this->assertEquals('approved', $profile->verification_status);
    }
}
