<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $rows = [
            ['invoice_reversal', 'Invoice Reversal (Admin Delete)', 'in', 100],  // reverses a SALE (out → add back)
            ['return_reversal', 'Return Reversal (Admin Delete)', 'out', 101],   // reverses a RETURN_IN (in → remove back)
            ['adjustment_reversal', 'Adjustment Reversal (Admin Delete)', 'out', 102], // reverses an ADJUSTMENT
            ['transfer_reversal', 'Transfer Reversal (Admin Delete)', 'in', 103],     // adds stock back to source branch
            ['damage_reversal', 'Damage Reversal (Admin Delete)', 'in', 104],         // reverses a DAMAGE (out → add back)
        ];

        $hasTenant = Schema::hasColumn('movement_types', 'tenant_id');
        $tenantId = $hasTenant ? (DB::table('movement_types')->value('tenant_id') ?? 1) : null;

        foreach ($rows as [$code, $name, $direction, $sort]) {
            $existing = DB::table('movement_types')->where('code', $code)->exists();
            if ($existing) {
                continue;
            }

            $row = [
                'code' => $code,
                'name' => $name,
                'direction' => $direction,
                'sort_order' => $sort,
                'is_active' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ];

            if ($hasTenant) {
                $row['tenant_id'] = $tenantId;
            }

            DB::table('movement_types')->insert($row);
        }
    }

    public function down(): void
    {
        DB::table('movement_types')
            ->whereIn('code', ['invoice_reversal', 'return_reversal', 'adjustment_reversal', 'transfer_reversal', 'damage_reversal'])
            ->delete();
    }
};
