<?php

namespace Tests\Feature;

use App\Models\Event;
use App\Models\EventMediaAsset;
use App\Models\EventPackage;
use App\Models\MediaStorageTarget;
use App\Models\Package;
use App\Models\Tenant;
use App\Services\Packages\PackageLimitEvaluator;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class TenantLimitEnforcementTest extends TestCase
{
    use RefreshDatabase;

    public function test_photo_upload_blocks_when_tenant_photo_limit_reached(): void
    {
        $tenant = Tenant::factory()->create([
            'max_photos_per_event' => 2,
            'max_storage_mb' => 0,
        ]);
        $event = Event::factory()->create(['tenant_id' => $tenant->id]);
        $package = Package::factory()->create([
            'max_photos' => 10,
            'type' => 'endcustomer',
        ]);

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

        $violation = app(PackageLimitEvaluator::class)
            ->assessPhotoUpload($tenant, $event->id, $event);

        $this->assertNotNull($violation);
        $this->assertSame('tenant_photo_limit_exceeded', $violation['code']);
    }

    public function test_photo_upload_blocks_when_tenant_storage_limit_reached(): void
    {
        $tenant = Tenant::factory()->create([
            'max_photos_per_event' => 0,
            'max_storage_mb' => 1,
        ]);
        $event = Event::factory()->create(['tenant_id' => $tenant->id]);
        $package = Package::factory()->create([
            'max_photos' => 10,
            'type' => 'endcustomer',
        ]);

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

        $storageTarget = MediaStorageTarget::create([
            'key' => 'local',
            'name' => 'Local Storage',
            'driver' => 'local',
            'config' => [],
            'is_hot' => true,
            'is_default' => true,
            'is_active' => true,
            'priority' => 1,
        ]);

        EventMediaAsset::create([
            'event_id' => $event->id,
            'media_storage_target_id' => $storageTarget->id,
            'variant' => 'original',
            'disk' => 'local',
            'path' => 'events/'.$event->id.'/photos/test.jpg',
            'size_bytes' => 1024 * 1024,
            'status' => 'hot',
        ]);

        $violation = app(PackageLimitEvaluator::class)
            ->assessPhotoUpload($tenant, $event->id, $event, 0);

        $this->assertNotNull($violation);
        $this->assertSame('tenant_storage_limit_exceeded', $violation['code']);
    }
}
