<?php

namespace Database\Seeders;

use App\Models\Tenant;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        // Create roles
        $roles = ['super_admin', 'admin', 'user'];
        foreach ($roles as $role) {
            Role::firstOrCreate(['name' => $role, 'guard_name' => 'sanctum']);
        }

        // Create super admin (no tenant)
        $superAdmin = User::firstOrCreate(
            ['email' => env('SUPER_ADMIN_EMAIL', 'admin@numerixpro.com')],
            [
                'name'     => 'Super Admin',
                'password' => Hash::make(env('SUPER_ADMIN_PASSWORD', 'change_me')),
            ]
        );
        $superAdmin->assignRole('super_admin');

        // Seed demo tenant + user (for local dev testing)
        if (app()->isLocal()) {
            $demoTenant = Tenant::firstOrCreate(
                ['name' => 'Demo Agency'],
                [
                    'plan'               => Tenant::PLAN_AGENCY,
                    'status'             => Tenant::STATUS_ACTIVE,
                    'subscription_start' => now(),
                    'subscription_end'   => now()->addYear(),
                    'default_country'    => 'PK',
                ]
            );

            $demoUser = User::firstOrCreate(
                ['email' => 'demo@agency.com'],
                [
                    'name'      => 'Demo User',
                    'password'  => Hash::make('password'),
                    'tenant_id' => $demoTenant->id,
                ]
            );
            $demoUser->assignRole('admin');

            // Pro plan tenant
            $proTenant = Tenant::firstOrCreate(
                ['name' => 'Pro Corp'],
                [
                    'plan'               => Tenant::PLAN_PRO,
                    'status'             => Tenant::STATUS_ACTIVE,
                    'subscription_start' => now(),
                    'subscription_end'   => now()->addMonth(),
                    'default_country'    => 'PK',
                ]
            );

            $proUser = User::firstOrCreate(
                ['email' => 'user@procorp.com'],
                [
                    'name'      => 'Pro User',
                    'password'  => Hash::make('password'),
                    'tenant_id' => $proTenant->id,
                ]
            );
            $proUser->assignRole('admin');
        }

        $this->command->info('Database seeded successfully.');
        $this->command->info('Super Admin: ' . env('SUPER_ADMIN_EMAIL') . ' / ' . env('SUPER_ADMIN_PASSWORD'));
        if (app()->isLocal()) {
            $this->command->info('Demo Agency: demo@agency.com / password');
            $this->command->info('Pro Corp: user@procorp.com / password');
        }
    }
}
