<?php

namespace Tests\Feature\Tenant;

use App\Models\Event;
use App\Models\EventPackage;
use App\Models\Package;
use Carbon\Carbon;

class EventAddonControllerTest extends TenantTestCase
{
    public function test_tenant_admin_can_apply_addons(): void
    {
        $package = Package::factory()->endcustomer()->create([
            'max_photos' => 100,
            'max_guests' => 50,
            'gallery_days' => 7,
        ]);

        $event = Event::factory()->for($this->tenant)->create([
            'status' => 'published',
        ]);

        $eventPackage = EventPackage::create([
            'event_id' => $event->id,
            'package_id' => $package->id,
            'purchased_price' => $package->price,
            'purchased_at' => now()->subDay(),
            'used_photos' => 10,
            'used_guests' => 5,
            'gallery_expires_at' => Carbon::now()->addDays(7),
        ]);

        $originalExpiry = $eventPackage->gallery_expires_at->copy();

        $response = $this->authenticatedRequest('POST', "/api/v1/tenant/events/{$event->slug}/addons/apply", [
            'extra_photos' => 50,
            'extra_guests' => 25,
            'extend_gallery_days' => 3,
            'reason' => 'Manual boost for event',
        ]);

        $response->assertOk();
        $response->assertJsonPath('data.limits.photos.limit', 150);
        $response->assertJsonPath('data.limits.guests.limit', 75);

        $eventPackage->refresh();

        $this->assertSame(50, $eventPackage->extra_photos);
        $this->assertSame(25, $eventPackage->extra_guests);
        $this->assertSame(3, $eventPackage->extra_gallery_days);
        $this->assertTrue($eventPackage->gallery_expires_at->isSameDay($originalExpiry->addDays(3)));
    }

    public function test_validation_fails_when_no_addons_provided(): void
    {
        $package = Package::factory()->endcustomer()->create();

        $event = Event::factory()->for($this->tenant)->create([
            'status' => 'published',
        ]);

        EventPackage::create([
            'event_id' => $event->id,
            'package_id' => $package->id,
            'purchased_price' => $package->price,
            'purchased_at' => now(),
            'used_photos' => 0,
            'used_guests' => 0,
            'gallery_expires_at' => now()->addDays(7),
        ]);

        $response = $this->authenticatedRequest('POST', "/api/v1/tenant/events/{$event->slug}/addons/apply", []);

        $response->assertStatus(422);
        $response->assertJsonValidationErrors('addons');
    }
}
