<?php

namespace Database\Seeders;

use App\Models\Branch;
use App\Models\User;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        // Run permission and role seeders first
        $this->call([
            PermissionSeeder::class,
            RoleSeeder::class,
            AdminUserSeeder::class,
            BatchSizeConfigSeeder::class,
            ExpenseCategorySeeder::class,
        ]);

        // ── Tenant system ──────────────────────────────────────────────────
        // Must run after users/roles so we can link the owner.
        $this->call([DefaultTenantSeeder::class]);

        // Create default branch
        $branch = Branch::firstOrCreate([
            'code' => 'MAIN',
        ], [
            'name' => 'Main Branch',
            'address' => '123 Main Street',
            'phone' => '+1234567890',
            'email' => 'main@creamyutopia.com',
            'is_active' => true,
            'settings' => ['stock_restriction_enabled' => true],
        ]);

        // Create super admin user
        $superAdmin = User::firstOrCreate([
            'email' => 'admin@creamyutopia.com',
        ], [
            'name' => 'Super Admin',
            'password' => bcrypt('password'),
            'branch_id' => null,
        ]);
        $superAdmin->assignRole('super-admin');

        // Create branch admin
        $branchAdmin = User::firstOrCreate([
            'email' => 'branch@creamyutopia.com',
        ], [
            'name' => 'Branch Admin',
            'password' => bcrypt('password'),
            'branch_id' => $branch->id,
        ]);
        $branchAdmin->assignRole('branch-admin');
    }
}
