<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\ChartOfAccount;
use App\Models\Account;
use App\Models\Contact;
use App\Services\ContactService;

class TestChartOfAccountsIntegration extends Command
{
    protected $signature = 'test:chart-of-accounts-integration';
    protected $description = 'Test Chart of Accounts integration with Contact module';

    public function handle()
    {
        $this->info('🧪 Testing Chart of Accounts Integration...');
        $this->newLine();

        // Test 1: Check Chart of Accounts structure
        $this->info('1. Testing Chart of Accounts structure...');
        try {
            $rootAccounts = ChartOfAccount::root()->get();
            $this->info("  ✓ Found " . $rootAccounts->count() . " root accounts");

            foreach ($rootAccounts as $root) {
                $this->info("    - {$root->name} ({$root->code}) - {$root->type}");
                $children = $root->children()->count();
                if ($children > 0) {
                    $this->info("      └─ {$children} sub-accounts");
                }
            }
        } catch (\Exception $e) {
            $this->error('  ✗ Chart of Accounts structure test failed: ' . $e->getMessage());
            return 1;
        }

        // Test 2: Check specific account codes for Contact integration
        $this->info('2. Testing Contact integration account codes...');
        try {
            $customerAccounts = ChartOfAccount::where('code', '1121')->first();
            $vendorAccounts = ChartOfAccount::where('code', '2111')->first();
            $employeeAccounts = ChartOfAccount::where('code', '5211')->first();
            $shopOperations = ChartOfAccount::where('code', '5220')->first();

            if ($customerAccounts) {
                $this->info("  ✓ Customer Accounts found: {$customerAccounts->name} (Code: {$customerAccounts->code})");
            } else {
                $this->error('  ✗ Customer Accounts not found');
            }

            if ($vendorAccounts) {
                $this->info("  ✓ Vendor Accounts found: {$vendorAccounts->name} (Code: {$vendorAccounts->code})");
            } else {
                $this->error('  ✗ Vendor Accounts not found');
            }

            if ($employeeAccounts) {
                $this->info("  ✓ Employee Accounts found: {$employeeAccounts->name} (Code: {$employeeAccounts->code})");
            } else {
                $this->error('  ✗ Employee Accounts not found');
            }

            if ($shopOperations) {
                $this->info("  ✓ Shop Operations found: {$shopOperations->name} (Code: {$shopOperations->code})");
            } else {
                $this->error('  ✗ Shop Operations not found');
            }
        } catch (\Exception $e) {
            $this->error('  ✗ Contact integration account codes test failed: ' . $e->getMessage());
            return 1;
        }

        // Test 3: Test ContactService account creation
        $this->info('3. Testing ContactService account creation...');
        try {
            $contactService = app(ContactService::class);
            $this->info('  ✓ ContactService instantiated successfully');
        } catch (\Exception $e) {
            $this->error('  ✗ ContactService instantiation failed: ' . $e->getMessage());
            return 1;
        }

        // Test 4: Check existing accounts
        $this->info('4. Checking existing accounts...');
        try {
            $totalAccounts = Account::count();
            $contactAccounts = Account::where('model_type', 'contact')->count();
            $userAccounts = Account::where('model_type', 'user')->count();
            $accountsWithChart = Account::whereNotNull('chart_of_account_id')->count();

            $this->info("  ✓ Total accounts: {$totalAccounts}");
            $this->info("  ✓ Contact accounts: {$contactAccounts}");
            $this->info("  ✓ User accounts: {$userAccounts}");
            $this->info("  ✓ Accounts with Chart of Accounts: {$accountsWithChart}");
        } catch (\Exception $e) {
            $this->error('  ✗ Account checking failed: ' . $e->getMessage());
            return 1;
        }

        // Test 5: Test hierarchical relationships
        $this->info('5. Testing hierarchical relationships...');
        try {
            $assets = ChartOfAccount::where('code', '1000')->first();
            if ($assets) {
                $currentAssets = $assets->children()->first();
                if ($currentAssets) {
                    $accountsReceivable = $currentAssets->children()->where('code', '1120')->first();
                    if ($accountsReceivable) {
                        $customerAccounts = $accountsReceivable->children()->where('code', '1121')->first();
                        if ($customerAccounts) {
                            $this->info("  ✓ Hierarchical path: Assets → Current Assets → Accounts Receivable → Customer Accounts");
                        } else {
                            $this->error('  ✗ Customer Accounts not found in hierarchy');
                        }
                    } else {
                        $this->error('  ✗ Accounts Receivable not found in hierarchy');
                    }
                } else {
                    $this->error('  ✗ Current Assets not found in hierarchy');
                }
            } else {
                $this->error('  ✗ Assets root account not found');
            }
        } catch (\Exception $e) {
            $this->error('  ✗ Hierarchical relationships test failed: ' . $e->getMessage());
            return 1;
        }

        $this->newLine();
        $this->info('✅ Chart of Accounts Integration test completed successfully!');
        $this->info('The system is ready for automatic account creation when contacts are created.');
        $this->newLine();
        $this->info('🎯 Integration Summary:');
        $this->info('   - Customer contacts will get accounts under Code 1121 (Assets → Current Assets → Accounts Receivable → Customer Accounts)');
        $this->info('   - Vendor contacts will get accounts under Code 2111 (Liabilities → Current Liabilities → Accounts Payable → Vendor Accounts)');
        $this->info('   - Employee contacts will get accounts under Code 5211 (Expenses → Operating Expenses → Salaries & Wages → Employee Accounts)');
        $this->info('   - Shop Manager contacts will get dual accounts: Employee (5211) + Shop Operations (5220)');

        return 0;
    }
}
