<?php

use App\Enums\ConsultationStatus;
use App\Models\Consultation;
use App\Models\User;

it('prevents unauthorized users from downloading calendar file', function () {
    $owner = User::factory()->create();
    $other = User::factory()->create();
    $consultation = Consultation::factory()->approved()->for($owner)->create();

    $this->actingAs($other)
        ->get(route('client.consultations.calendar', $consultation))
        ->assertForbidden();
});

it('prevents download for non-approved consultations', function () {
    $user = User::factory()->create();
    $consultation = Consultation::factory()->for($user)->create([
        'status' => ConsultationStatus::Pending,
    ]);

    $this->actingAs($user)
        ->get(route('client.consultations.calendar', $consultation))
        ->assertNotFound();
});

it('allows owner to download calendar file for approved consultation', function () {
    $user = User::factory()->create();
    $consultation = Consultation::factory()->approved()->for($user)->create();

    $this->actingAs($user)
        ->get(route('client.consultations.calendar', $consultation))
        ->assertOk()
        ->assertHeader('Content-Type', 'text/calendar; charset=utf-8');
});

it('requires authentication to download calendar file', function () {
    $consultation = Consultation::factory()->approved()->create();

    $this->get(route('client.consultations.calendar', $consultation))
        ->assertRedirect(route('login'));
});

it('returns calendar file with correct filename', function () {
    $user = User::factory()->create();
    $consultation = Consultation::factory()->approved()->for($user)->create([
        'booking_date' => '2024-05-15',
    ]);

    $response = $this->actingAs($user)
        ->get(route('client.consultations.calendar', $consultation));

    $response->assertOk();
    expect($response->headers->get('Content-Disposition'))
        ->toContain('consultation-2024-05-15.ics');
});

it('prevents download for cancelled consultations', function () {
    $user = User::factory()->create();
    $consultation = Consultation::factory()->for($user)->create([
        'status' => ConsultationStatus::Cancelled,
    ]);

    $this->actingAs($user)
        ->get(route('client.consultations.calendar', $consultation))
        ->assertNotFound();
});

it('prevents download for completed consultations', function () {
    $user = User::factory()->create();
    $consultation = Consultation::factory()->for($user)->create([
        'status' => ConsultationStatus::Completed,
    ]);

    $this->actingAs($user)
        ->get(route('client.consultations.calendar', $consultation))
        ->assertNotFound();
});
