<?php

namespace Database\Seeders;

use App\Models\EventPurchase;
use App\Models\Package;
use App\Models\PackagePurchase;
use App\Models\Tenant;
use App\Models\TenantPackage;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DemoTenantSeeder extends Seeder
{
    public function run(): void
    {
        $email = 'tenant-demo@fotospiel.app';
        $password = config('seeding.demo_tenant_password', 'Demo1234!');
        $package = Package::query()
            ->where('slug', 'standard')
            ->first();

        if (! $package) {
            $package = Package::query()
                ->where('type', 'endcustomer')
                ->orderBy('price')
                ->first();
        }

        if (! $package) {
            $package = Package::query()->orderBy('price')->first();
        }

        if (! $package) {
            $this->command?->warn('Skipped DemoTenantSeeder: no packages available.');

            return;
        }

        $user = User::query()->firstOrCreate(
            ['email' => $email],
            [
                'username' => 'tenant-demo',
                'password' => Hash::make($password),
                'first_name' => 'Demo',
                'last_name' => 'Tenant',
                'address' => 'Demo Straße 1, 12345 Musterstadt',
                'phone' => '+49 123 456789',
                'role' => 'tenant_admin',
                'pending_purchase' => false,
                'email_verified_at' => now(),
            ]
        );

        if (! $user->email_verified_at) {
            $user->forceFill(['email_verified_at' => now()])->save();
        }

        if ($user->role !== 'tenant_admin') {
            $user->forceFill(['role' => 'tenant_admin'])->save();
        }

        $tenant = Tenant::query()->firstOrCreate(
            ['slug' => 'demo-tenant'],
            [
                'user_id' => $user->id,
                'name' => 'Demo Tenant',
                'email' => $user->email,
                'is_active' => true,
                'is_suspended' => false,
                'subscription_tier' => $package->type,
                'subscription_status' => 'active',
                'settings' => [
                    'contact_email' => $user->email,
                    'branding' => [
                        'logo_url' => null,
                        'primary_color' => '#FF5A5F',
                        'secondary_color' => '#FFF8F5',
                    ],
                ],
            ]
        );

        if ($tenant->wasRecentlyCreated && ! $tenant->slug) {
            $tenant->forceFill(['slug' => Str::slug('demo-tenant-'.$tenant->getKey())])->save();
        }

        if ($user->tenant_id !== $tenant->id) {
            $user->forceFill(['tenant_id' => $tenant->id])->save();
        }

        $purchasedAt = now()->subDays(7);

        TenantPackage::query()->updateOrCreate(
            [
                'tenant_id' => $tenant->id,
                'package_id' => $package->id,
            ],
            [
                'price' => $package->price,
                'active' => true,
                'purchased_at' => $purchasedAt,
                'expires_at' => now()->addMonths(6),
                'used_events' => 0,
            ]
        );

        PackagePurchase::query()->updateOrCreate(
            [
                'tenant_id' => $tenant->id,
                'package_id' => $package->id,
                'provider_id' => 'demo-seed',
            ],
            [
                'event_id' => null,
                'price' => $package->price,
                'type' => $package->type === 'reseller' ? 'reseller_subscription' : 'endcustomer_event',
                'purchased_at' => $purchasedAt,
                'metadata' => [
                    'seeded' => true,
                    'note' => 'Demo tenant seed purchase',
                ],
                'ip_address' => null,
                'user_agent' => null,
            ]
        );

        EventPurchase::query()->updateOrCreate(
            [
                'tenant_id' => $tenant->id,
                'provider' => 'demo-seed',
            ],
            [
                'events_purchased' => 1,
                'amount' => $package->price,
                'currency' => 'EUR',
                'status' => 'completed',
                'purchased_at' => $purchasedAt,
            ]
        );

        $this->command?->info(sprintf(
            'Demo tenant ready. Login with %s / %s',
            $email,
            $password
        ));
    }
}
