<?php

namespace Tests\Feature;

use App\Models\Worker;
use App\Models\ReportReason;
use App\Models\SupportTicket;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class WorkerSupportTicketApiTest extends TestCase
{
    use RefreshDatabase;

    protected $worker;
    protected $token;
    protected $reason;

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

        $this->token = 'worker-test-token-789';
        
        $category = \App\Models\WorkerCategory::create([
            'name' => 'Housemaid',
        ]);

        $this->worker = Worker::create([
            'name' => 'John Worker',
            'email' => 'worker@example.com',
            'phone' => '+971500000009',
            'password' => bcrypt('password'),
            'api_token' => $this->token,
            'status' => 'Available',
            'category_id' => $category->id,
            'nationality' => 'Ethiopian',
            'age' => 28,
            'salary' => 1500.00,
            'availability' => 'Immediate',
            'experience' => '2 Years',
            'religion' => 'Christian',
            'bio' => 'Experienced helper.',
        ]);

        $this->reason = ReportReason::create([
            'reason' => 'App crashes when loading data',
            'status' => 'active',
            'type' => 'support',
        ]);
    }

    public function test_worker_can_create_ticket_with_reason_and_voice_note()
    {
        Storage::fake('public');

        $voiceFile = UploadedFile::fake()->create('note.mp3', 500, 'audio/mpeg');

        $response = $this->withHeaders([
            'Authorization' => 'Bearer ' . $this->token,
        ])->postJson('/api/workers/tickets', [
            'subject' => 'Issue with login',
            'description' => 'I cannot log in to the application.',
            'priority' => 'high',
            'reason_id' => $this->reason->id,
            'voice_note' => $voiceFile,
        ]);

        $response->assertStatus(201)
            ->assertJsonStructure([
                'success',
                'message',
                'ticket' => [
                    'id',
                    'ticket_number',
                    'subject',
                    'description',
                    'reason_id',
                    'reason_name',
                    'voice_note_url',
                    'status',
                    'priority',
                    'created_at',
                ]
            ]);

        $ticket = SupportTicket::first();
        $this->assertNotNull($ticket);
        $this->assertEquals('Issue with login', $ticket->subject);
        $this->assertEquals($this->reason->id, $ticket->reason_id);
        $this->assertNotNull($ticket->voice_note_path);

        Storage::disk('public')->assertExists($ticket->voice_note_path);
    }
}
