<?php

use App\Services\AccountingService;
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
{
    public function up(): void
    {
        Schema::table('communication_unit_wallets', function (Blueprint $table): void {
            $table->decimal('cost_balance', 14, 2)->default(0)->after('balance_units');
            $table->decimal('total_credited_amount', 14, 2)->default(0)->after('total_credited_units');
            $table->decimal('total_used_cost', 14, 2)->default(0)->after('total_used_units');
        });

        Schema::table('communication_unit_transactions', function (Blueprint $table): void {
            $table->decimal('cost_amount', 14, 2)->default(0)->after('amount');
        });

        $rows = [];

        DB::table('tenants')
            ->select(['id'])
            ->orderBy('id')
            ->get()
            ->each(function ($tenant) use (&$rows): void {
                foreach (AccountingService::DEFAULT_ACCOUNTS as [$code, $name, $type]) {
                    $rows[] = [
                        'tenant_id' => $tenant->id,
                        'code' => $code,
                        'name' => $name,
                        'type' => $type,
                        'balance' => 0,
                        'is_system' => true,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ];
                }
            });

        if ($rows !== []) {
            DB::table('accounting_accounts')->insertOrIgnore($rows);
        }
    }

    public function down(): void
    {
        Schema::table('communication_unit_transactions', function (Blueprint $table): void {
            $table->dropColumn('cost_amount');
        });

        Schema::table('communication_unit_wallets', function (Blueprint $table): void {
            $table->dropColumn(['cost_balance', 'total_credited_amount', 'total_used_cost']);
        });
    }
};
