<?php

namespace Database\Seeders;

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

class AccessibleUserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Create or get roles
        $superAdminRole = Role::firstOrCreate(['name' => 'super-admin']);
        $adminRole = Role::firstOrCreate(['name' => 'admin']);
        $userRole = Role::firstOrCreate(['name' => 'user']);

        // Get the first tenant or create one if none exists
        $tenant = \App\Models\Tenant::first();
        if (!$tenant) {
            $tenant = \App\Models\Tenant::create([
                'name' => 'Default Tenant',
                'domain' => 'defaultdomain.com',
                'subdomain' => 'defaultsubdomain',
            ]);
        }

        // Create a super-admin user with full access
        $superAdminUser = User::updateOrCreate(
            ['email' => 'superadmin@example.com'],
            [
                'name' => 'Super Admin',
                'password' => Hash::make('super123'),
                'tenant_id' => $tenant->id,
            ]
        );
        $superAdminUser->assignRole($superAdminRole);

        // Create an admin user with full access
        $adminUser = User::updateOrCreate(
            ['email' => 'thillaiyadiking@gmail.com'],
            [
                'name' => 'Admin User',
                'password' => Hash::make('12345678'),
                'tenant_id' => $tenant->id,
            ]
        );
        $adminUser->assignRole($adminRole);

        // Create an active subscription for the tenant
        $basicPlan = \App\Models\Plan::where('name', 'Basic')->first();
        if ($basicPlan) {
            \App\Models\Subscription::updateOrCreate(
                ['tenant_id' => $tenant->id],
                [
                    'plan_id' => $basicPlan->id,
                    'status' => 'active',
                    'start_date' => now(),
                    'end_date' => null,
                    'price' => $basicPlan->price,
                    'interval' => $basicPlan->interval,
                ]
            );
        }

        // Create a regular user with limited access
        $normalUser = User::updateOrCreate(
            ['email' => 'user@example.com'],
            [
                'name' => 'Normal User',
                'password' => Hash::make('password123'),
                'tenant_id' => $tenant->id,
            ]
        );
        $normalUser->assignRole($userRole);

        // You can add more users here with different roles and permissions as needed
    }
}
