<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $now = now();

        $maxClaim = (int) DB::table('transaction_claims')
            ->selectRaw('MAX(CAST(SUBSTR(claim_number, 5) AS INTEGER)) as v')
            ->value('v');

        $maxTxn = (int) DB::table('transactions')
            ->selectRaw('MAX(CAST(SUBSTR(transaction_number, 5) AS INTEGER)) as v')
            ->value('v');

        $seeds = [
            ['sequence_key' => 'claim',       'next_value' => max(1, $maxClaim + 1)],
            ['sequence_key' => 'transaction',  'next_value' => max(1, $maxTxn + 1)],
        ];

        foreach ($seeds as $seed) {
            DB::table('document_sequences')->upsert(
                array_merge($seed, ['created_at' => $now, 'updated_at' => $now]),
                ['sequence_key'],
                ['next_value', 'updated_at'],
            );
        }
    }

    public function down(): void
    {
        DB::table('document_sequences')->whereIn('sequence_key', ['claim', 'transaction'])->delete();
    }
};
