<?php

namespace Database\Seeders;

use App\Models\Branch;
use App\Models\Counter;
use App\Models\Department;
use App\Models\Employee;
use App\Models\Plan;
use App\Models\Role;
use App\Models\Subscription;
use App\Models\Tenant;
use App\Models\User;
use App\Models\UserType;
use App\Services\UaeDefaultServiceCatalogService;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class SampleTenantSeeder extends Seeder
{
    public function run(): void
    {
        $platformType = UserType::where('slug', 'platform_user')->first();
        $tenantType = UserType::where('slug', 'tenant_user')->first();
        $superAdminRole = Role::where('slug', 'platform_super_admin')->first();

        // 1. Create Platform Super Admin
        $platformAdmin = User::updateOrCreate(
            ['email' => 'admin@platform.com'],
            [
                'tenant_id' => null,
                'user_type_id' => $platformType->id,
                'name' => 'Platform Administrator',
                'username' => 'superadmin',
                'password' => Hash::make('Password123!'),
                'language' => 'en',
                'timezone' => 'Asia/Dubai',
                'status' => 'active',
            ]
        );
        $platformAdmin->roles()->sync([$superAdminRole->id]);

        // 2. Create Sample Tenant: Al Madina Typing Center
        $plan = Plan::where('slug', 'professional')->first();
        $tenant = Tenant::updateOrCreate(
            ['slug' => 'al-madina-typing'],
            [
                'company_name' => 'Al Madina Typing Center LLC',
                'legal_name' => 'Al Madina Typing & Government Transactions LLC',
                'email' => 'info@almadina.ae',
                'mobile' => '+97142001234',
                'country' => 'UAE',
                'emirate' => 'Dubai',
                'trn' => '100293847500003',
                'trade_license_number' => 'TL-9847291',
                'trade_license_expiry' => '2027-12-31',
                'default_language' => 'en',
                'timezone' => 'Asia/Dubai',
                'currency' => 'AED',
                'status' => 'active',
            ]
        );

        // Subscription
        $sub = Subscription::create([
            'tenant_id' => $tenant->id,
            'plan_id' => $plan->id,
            'status' => 'active',
            'starts_at' => now(),
            'ends_at' => now()->addYear(),
        ]);
        $tenant->update(['subscription_id' => $sub->id]);

        // 3. Create Branches
        $mainBranch = Branch::updateOrCreate(
            ['tenant_id' => $tenant->id, 'code' => 'DXB-01'],
            [
                'name' => 'Dubai Main Branch',
                'emirate' => 'Dubai',
                'address' => 'Sheikh Zayed Road, Building 4, Dubai',
                'phone' => '+97142001234',
                'email' => 'dxb1@almadina.ae',
                'is_main' => true,
                'status' => 'active',
            ]
        );

        $qusaisBranch = Branch::updateOrCreate(
            ['tenant_id' => $tenant->id, 'code' => 'DXB-02'],
            [
                'name' => 'Al Qusais Branch',
                'emirate' => 'Dubai',
                'address' => 'Damascus Street, Al Qusais 2, Dubai',
                'phone' => '+97142005678',
                'email' => 'dxb2@almadina.ae',
                'is_main' => false,
                'status' => 'active',
            ]
        );

        $deiraBranch = Branch::updateOrCreate(
            ['tenant_id' => $tenant->id, 'code' => 'DXB-03'],
            [
                'name' => 'Deira Branch',
                'emirate' => 'Dubai',
                'address' => 'Al Rigga Road, Deira, Dubai',
                'phone' => '+97142009012',
                'email' => 'dxb3@almadina.ae',
                'is_main' => false,
                'status' => 'active',
            ]
        );

        // 4. Create Departments & Counters
        $frontDept = Department::create(['tenant_id' => $tenant->id, 'branch_id' => $mainBranch->id, 'name' => 'Front Desk & Reception', 'code' => 'FD']);
        $typingDept = Department::create(['tenant_id' => $tenant->id, 'branch_id' => $mainBranch->id, 'name' => 'Typing & Processing', 'code' => 'TYP']);
        $accountsDept = Department::create(['tenant_id' => $tenant->id, 'branch_id' => $mainBranch->id, 'name' => 'Accounts & Finance', 'code' => 'ACC']);
        $proDept = Department::create(['tenant_id' => $tenant->id, 'branch_id' => $mainBranch->id, 'name' => 'PRO Relations', 'code' => 'PRO']);

        $counter1 = Counter::create(['tenant_id' => $tenant->id, 'branch_id' => $mainBranch->id, 'department_id' => $frontDept->id, 'name' => 'Counter 1 (General)', 'code' => 'C1']);
        $counter2 = Counter::create(['tenant_id' => $tenant->id, 'branch_id' => $mainBranch->id, 'department_id' => $typingDept->id, 'name' => 'Counter 2 (Amer Services)', 'code' => 'C2']);

        // 5. Create System Tenant Roles for this Tenant
        $rolesSeed = [
            'owner' => Role::where('slug', 'owner')->whereNull('tenant_id')->first(),
            'company_admin' => Role::where('slug', 'company_admin')->whereNull('tenant_id')->first(),
            'branch_manager' => Role::where('slug', 'branch_manager')->whereNull('tenant_id')->first(),
            'receptionist' => Role::where('slug', 'receptionist')->whereNull('tenant_id')->first(),
            'typist' => Role::where('slug', 'typist')->whereNull('tenant_id')->first(),
            'processing_supervisor' => Role::where('slug', 'processing_supervisor')->whereNull('tenant_id')->first(),
            'pro' => Role::where('slug', 'pro')->whereNull('tenant_id')->first(),
            'cashier' => Role::where('slug', 'cashier')->whereNull('tenant_id')->first(),
            'accountant' => Role::where('slug', 'accountant')->whereNull('tenant_id')->first(),
            'hr' => Role::where('slug', 'hr')->whereNull('tenant_id')->first(),
            'renewal_executive' => Role::where('slug', 'renewal_executive')->whereNull('tenant_id')->first(),
        ];

        // 6. Employee & User Account Mapping Helper
        $usersToCreate = [
            [
                'code' => 'EMP-001',
                'first' => 'Mohammed',
                'last' => 'Al Mansoori',
                'email' => 'owner@almadina.ae',
                'username' => 'owner',
                'role' => 'owner',
                'designation' => 'Managing Director',
                'branch' => $mainBranch->id,
            ],
            [
                'code' => 'EMP-002',
                'first' => 'Rashid',
                'last' => 'Khalfan',
                'email' => 'manager@almadina.ae',
                'username' => 'manager',
                'role' => 'branch_manager',
                'designation' => 'Branch Manager',
                'branch' => $mainBranch->id,
            ],
            [
                'code' => 'EMP-003',
                'first' => 'Fatima',
                'last' => 'Zahra',
                'email' => 'reception@almadina.ae',
                'username' => 'receptionist',
                'role' => 'receptionist',
                'designation' => 'Front Desk Receptionist',
                'branch' => $mainBranch->id,
            ],
            [
                'code' => 'EMP-004',
                'first' => 'Suresh',
                'last' => 'Kumar',
                'email' => 'typist@almadina.ae',
                'username' => 'typist',
                'role' => 'typist',
                'designation' => 'Senior Typist',
                'branch' => $mainBranch->id,
            ],
            [
                'code' => 'EMP-005',
                'first' => 'Tariq',
                'last' => 'Mahmood',
                'email' => 'supervisor@almadina.ae',
                'username' => 'supervisor',
                'role' => 'processing_supervisor',
                'designation' => 'Processing Supervisor',
                'branch' => $mainBranch->id,
            ],
            [
                'code' => 'EMP-006',
                'first' => 'Salem',
                'last' => 'Al Hamadi',
                'email' => 'pro@almadina.ae',
                'username' => 'pro',
                'role' => 'pro',
                'designation' => 'Public Relations Officer',
                'branch' => $mainBranch->id,
            ],
            [
                'code' => 'EMP-007',
                'first' => 'Anil',
                'last' => 'Sharma',
                'email' => 'cashier@almadina.ae',
                'username' => 'cashier',
                'role' => 'cashier',
                'designation' => 'Head Cashier',
                'branch' => $mainBranch->id,
            ],
            [
                'code' => 'EMP-008',
                'first' => 'Aisha',
                'last' => 'Hassan',
                'email' => 'accountant@almadina.ae',
                'username' => 'accountant',
                'role' => 'accountant',
                'designation' => 'Chief Accountant',
                'branch' => $mainBranch->id,
            ],
            [
                'code' => 'EMP-009',
                'first' => 'Mariam',
                'last' => 'Al Hosani',
                'email' => 'hr@almadina.ae',
                'username' => 'hrmanager',
                'role' => 'hr',
                'designation' => 'HR Manager',
                'branch' => $mainBranch->id,
            ],
            [
                'code' => 'EMP-010',
                'first' => 'Bilal',
                'last' => 'Ahmed',
                'email' => 'renewals@almadina.ae',
                'username' => 'renewals',
                'role' => 'renewal_executive',
                'designation' => 'Renewal Executive',
                'branch' => $mainBranch->id,
            ],
        ];

        foreach ($usersToCreate as $u) {
            $emp = Employee::updateOrCreate(
                ['tenant_id' => $tenant->id, 'employee_code' => $u['code']],
                [
                    'branch_id' => $u['branch'],
                    'first_name' => $u['first'],
                    'last_name' => $u['last'],
                    'full_name' => $u['first'].' '.$u['last'],
                    'email' => $u['email'],
                    'mobile' => '+97150'.rand(1000000, 9999999),
                    'designation' => $u['designation'],
                    'status' => 'active',
                ]
            );

            $user = User::updateOrCreate(
                ['email' => $u['email']],
                [
                    'tenant_id' => $tenant->id,
                    'employee_id' => $emp->id,
                    'user_type_id' => $tenantType->id,
                    'name' => $emp->full_name,
                    'mobile' => $emp->mobile,
                    'username' => $u['username'],
                    'password' => Hash::make('Password123!'),
                    'default_branch_id' => $u['branch'],
                    'language' => 'en',
                    'timezone' => 'Asia/Dubai',
                    'status' => 'active',
                ]
            );

            $role = $rolesSeed[$u['role']] ?? null;
            if ($role) {
                $user->roles()->sync([$role->id]);
            }
            $user->allowedBranches()->sync([$mainBranch->id, $qusaisBranch->id, $deiraBranch->id]);
        }

        if (! app()->environment('testing')) {
            app(UaeDefaultServiceCatalogService::class)->ensureForTenant($tenant);
        }
    }
}
