<?php

namespace Tests\Feature;

use App\Models\Business;
use App\Models\ContractTemplate;
use App\Models\User;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class PdfPreviewRelativeUrlTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed(DatabaseSeeder::class);
        Storage::fake('local');
    }

    public function test_original_pdf_iframe_uses_same_origin_relative_url_instead_of_localhost(): void
    {
        [$admin,$template]=$this->pdfTemplate();

        $relative=route('admin.contract-templates.preview-source',$template,false);
        $response=$this->actingAs($admin)->get(route('admin.contract-templates.edit',$template));

        $response->assertOk();
        $response->assertSee('src="'.$relative.'"',false);
        $response->assertDontSee('src="http://localhost'.$relative.'"',false);
    }

    public function test_pdf_preview_route_allows_same_origin_iframe_but_normal_pages_remain_denied(): void
    {
        [$admin,$template]=$this->pdfTemplate();

        $preview=$this->actingAs($admin)->get(route('admin.contract-templates.preview-source',$template));
        $preview->assertOk()->assertHeader('Content-Type','application/pdf');
        $preview->assertHeader('X-Frame-Options','SAMEORIGIN');
        $this->assertStringContainsString("frame-ancestors 'self'",(string)$preview->headers->get('Content-Security-Policy'));

        $normal=$this->actingAs($admin)->get(route('admin.contract-templates.edit',$template));
        $normal->assertOk()->assertHeader('X-Frame-Options','DENY');
        $this->assertStringContainsString("frame-ancestors 'none'",(string)$normal->headers->get('Content-Security-Policy'));
    }

    /** @return array{0:User,1:ContractTemplate} */
    private function pdfTemplate(): array
    {
        $admin=User::where('username','admin')->firstOrFail();
        $business=Business::firstOrFail();
        $path='contract-templates/'.$business->id.'/relative-preview.pdf';
        Storage::disk('local')->put($path,"%PDF-1.4\n% test preview\n");

        $template=ContractTemplate::create([
            'business_id'=>$business->id,
            'name'=>'Relative PDF Preview',
            'version'=>1,
            'original_name'=>'relative-preview.pdf',
            'format'=>'pdf',
            'file_path'=>$path,
            'extracted_text'=>'PDF visual template · 1 page.',
            'blocks'=>[['id'=>'pdf:1','page'=>1,'width'=>210,'height'=>297]],
            'mappings'=>[],
            'required_signatories'=>['borrower'],
            'status'=>'draft',
            'is_default'=>false,
            'uploaded_by'=>$admin->id,
            'updated_by'=>$admin->id,
        ]);

        return [$admin,$template];
    }
}
