<?php

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

return new class extends Migration
{
    /**
     * Mirrors 2026_06_25_061448 (add_grn_reversal_movement_type): the
     * return-out reversal code seeds identically for every tenant, so the
     * migration inserts a single row using the first tenant's tenant_id.
     * LookupSeeder::seedMovementTypes() also carries the row (firstOrCreate)
     * for fresh installs and re-runs.
     */
    public function up(): void
    {
        $row = [
            'code' => 'return_out_reversal',
            'name' => 'Return to Supplier Reversal',
            'direction' => 'in',
            'sort_order' => 99,
            'is_active' => true,
            'created_at' => now(),
            'updated_at' => now(),
        ];

        if (Schema::hasColumn('movement_types', 'tenant_id')) {
            $row['tenant_id'] = DB::table('movement_types')->value('tenant_id') ?? 1;
        }

        // Mirrors 2026_06_29_000001: movement_types has a composite
        // (tenant_id, code) unique index, so `upsert($row, ['code'])` would
        // fail on SQLite ("ON CONFLICT clause does not match any PRIMARY KEY
        // or UNIQUE constraint"). Exists-check keeps it idempotent instead.
        if (! DB::table('movement_types')->where('code', 'return_out_reversal')->exists()) {
            DB::table('movement_types')->insert($row);
        }
    }

    public function down(): void
    {
        DB::table('movement_types')->where('code', 'return_out_reversal')->delete();
    }
};
