<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Tenant;
use App\Models\Plan;
use App\Models\Subscription;
use App\Services\TenantService;
use Illuminate\Support\Str;

class SubscriptionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $plans = Plan::all();

        if ($plans->isEmpty()) {
            $this->call(PlanSeeder::class);
            $plans = Plan::all();
        }

        // Get existing tenants
        $tenants = Tenant::all();

        // If no tenants, create a few dummy ones for demonstration
        if ($tenants->isEmpty()) {
            $this->createDummyTenants();
            $tenants = Tenant::all();
        }

        foreach ($tenants as $tenant) {
            // Check if tenant already has a subscription
            if (!$tenant->subscription) {
                $plan = $plans->random();
                
                // Randomize status
                $status = fake()->randomElement(['active', 'active', 'active', 'trialing', 'past_due', 'cancelled']);
                
                $startsAt = now()->subDays(rand(1, 60));
                $endsAt = null;
                $trialEndsAt = null;

                if ($status === 'trialing') {
                    $startsAt = now();
                    $trialEndsAt = now()->addDays(14);
                } else {
                    $endsAt = match($plan->interval) {
                        'daily' => $startsAt->copy()->addDay(),
                        'monthly' => $startsAt->copy()->addDays(30),
                        'yearly' => $startsAt->copy()->addDays(360),
                        default => $startsAt->copy()->addMonth(),
                    };
                }

                if ($status === 'cancelled') {
                    $endsAt = now()->subDays(rand(1, 10));
                }

                Subscription::create([
                    'tenant_id' => $tenant->id,
                    'plan_id' => $plan->id,
                    'status' => $status,
                    'starts_at' => $startsAt,
                    'ends_at' => $endsAt,
                    'trial_ends_at' => $trialEndsAt,
                ]);
            }
        }
    }

    protected function createDummyTenants()
    {
        // We won't actually create their databases here to save time/resources for this seeder,
        // we just want to populate the central DB lists for UI verification.
        // In a real scenario, use TenantService.
        
        $names = ['Fresh Mart', 'City Grocers', 'Green Valley', 'Organic Stop', 'Quick Pick'];

        foreach ($names as $name) {
            Tenant::create([
                'name' => $name,
                'domain' => Str::slug($name) . '.grocery-saas.local',
                'database_name' => 'tenant_' . Str::slug($name, '_'),
                'status' => 'active',
            ]);
        }
    }
}
