<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    private array $defaultCategories = [
        'Salary',
        'Fuel/Diesel',
        'Transportation',
        'Maintenance',
        'Office Supplies',
        'Utility Bills',
        'Internet',
        'Rent',
        'Security',
        'Marketing',
        'Repairs',
        'Bank Charges',
        'Tax',
        'Logistics',
    ];

    public function up(): void
    {
        Schema::table('expenses', function (Blueprint $table): void {
            if (! Schema::hasColumn('expenses', 'branch_id')) {
                $table->foreignId('branch_id')
                    ->nullable()
                    ->after('recorded_by')
                    ->constrained('branches')
                    ->nullOnDelete();
            }
        });

        $this->seedDefaultCategories();
    }

    public function down(): void
    {
        Schema::table('expenses', function (Blueprint $table): void {
            if (Schema::hasColumn('expenses', 'branch_id')) {
                $table->dropConstrainedForeignId('branch_id');
            }
        });
    }

    private function seedDefaultCategories(): void
    {
        if (! Schema::hasTable('expense_categories') || ! Schema::hasTable('tenants')) {
            return;
        }

        DB::table('tenants')
            ->select('id')
            ->orderBy('id')
            ->chunkById(100, function ($tenants): void {
                foreach ($tenants as $tenant) {
                    foreach ($this->defaultCategories as $category) {
                        DB::table('expense_categories')->updateOrInsert(
                            ['tenant_id' => $tenant->id, 'name' => $category],
                            [
                                'description' => $this->descriptionFor($category),
                                'is_active' => true,
                                'created_at' => now(),
                                'updated_at' => now(),
                            ]
                        );
                    }
                }
            });
    }

    private function descriptionFor(string $category): string
    {
        return match ($category) {
            'Salary' => 'Staff salaries, allowances, and payroll-related expenses.',
            'Fuel/Diesel' => 'Fuel, diesel, generator, and vehicle fueling costs.',
            'Transportation' => 'Transport fares, movement costs, and field operations travel.',
            'Maintenance' => 'Routine maintenance for office, vehicles, equipment, and facilities.',
            'Office Supplies' => 'Stationery, printing items, forms, and daily office consumables.',
            'Utility Bills' => 'Electricity, water, waste, and other utility payments.',
            'Internet' => 'Internet subscriptions, data plans, and connectivity costs.',
            'Rent' => 'Office rent, shop rent, and related property charges.',
            'Security' => 'Security services, guards, safety, and monitoring expenses.',
            'Marketing' => 'Promotions, adverts, branding, outreach, and sales campaigns.',
            'Repairs' => 'Repairs for assets, devices, office equipment, and facilities.',
            'Bank Charges' => 'Bank fees, transfer charges, POS charges, and account maintenance.',
            'Tax' => 'Taxes, levies, dues, and statutory payments.',
            'Logistics' => 'Courier, dispatch, delivery, and operational logistics.',
            default => 'Operating expense category.',
        };
    }
};
