<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Branch;
use App\Models\Member;
use App\Models\MessagingCredential;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\User;
use App\Support\OrganizationBranding;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class CareEmailBrandingTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

    protected Organization $organization;

    protected function setUp(): void
    {
        parent::setUp();
        $this->withoutMiddleware(EnsurePlatformSession::class);

        $this->user = User::create([
            'public_id' => 'test-user-brand-001',
            'name' => 'Test User',
            'email' => 'brand@example.com',
        ]);

        $this->organization = Organization::create([
            'owner_ref' => $this->user->public_id,
            'name' => 'Test Clinic',
            'slug' => 'test-clinic-brand',
            'timezone' => 'UTC',
            'settings' => ['onboarded' => true, 'facility_type' => 'clinic'],
        ]);

        Member::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'user_ref' => $this->user->public_id,
            'role' => 'hospital_admin',
        ]);

        Branch::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'name' => 'Main',
            'is_active' => true,
        ]);
    }

    public function test_patient_email_contains_organization_logo(): void
    {
        Storage::fake('public');

        $path = UploadedFile::fake()->image('clinic-logo.png', 400, 120)
            ->store('care/organizations/'.$this->organization->id, 'public');
        $this->organization->update(['logo_path' => $path, 'name' => 'Test Clinic']);

        $plain = 'lsk_live_'.str_repeat('d', 32);
        MessagingCredential::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'bird_api_key_encrypted' => Crypt::encryptString($plain),
            'bird_api_key_prefix' => substr($plain, 0, 16),
            'bird_from_email' => 'clinic@example.test',
            'bird_from_name' => 'Clinic',
            'bird_status' => MessagingCredential::STATUS_VALID,
            'bird_validated_at' => now(),
        ]);

        Http::fake([
            '*/api/smtp/send' => Http::response(['success' => true, 'message_id' => 'x']),
        ]);

        $patient = Patient::create([
            'uuid' => (string) \Illuminate\Support\Str::uuid(),
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => Branch::first()->id,
            'patient_number' => 'LC-BRAND-00001',
            'first_name' => 'Ada',
            'last_name' => 'Lovelace',
            'email' => 'ada@example.com',
        ]);

        $this->actingAs($this->user)
            ->post(route('care.patients.email', $patient), [
                'subject' => 'Appointment reminder',
                'body' => 'Please arrive 10 minutes early.',
            ])
            ->assertRedirect()
            ->assertSessionHas('success');

        $logoUrl = OrganizationBranding::emailLogoUrl($this->organization->fresh());

        Http::assertSent(function ($request) use ($logoUrl) {
            $html = $request['html'] ?? '';

            return str_contains($request->url(), '/api/smtp/send')
                && str_contains($html, 'Test Clinic')
                && str_contains($html, $logoUrl)
                && ! str_contains($html, 'ladillcare-logo')
                && str_contains($html, 'Sent via Ladill Care');
        });
    }
}
