<?php

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

/**
 * Makes the two databases mergeable.
 *
 * Auto-increment ids are per-database, so the same id can mean two different
 * expenses in Aiven and in the local mirror. A uuid is generated by the app
 * instead, which makes a row identifiable no matter where it was written.
 *
 * sync_queue holds writes made while the cloud was offline, in order.
 */
return new class extends Migration
{
    public function up(): void
    {
        foreach (['expenses', 'categories'] as $table) {
            Schema::table($table, function (Blueprint $t) {
                $t->uuid('uuid')->nullable()->after('id');
                $t->timestamp('synced_at')->nullable();
            });

            // Backfill whatever is already there, then lock the column down.
            DB::table($table)->whereNull('uuid')->orderBy('id')->each(function ($row) use ($table) {
                DB::table($table)->where('id', $row->id)->update(['uuid' => (string) Str::uuid()]);
            });

            Schema::table($table, function (Blueprint $t) {
                $t->unique('uuid');
            });
        }

        Schema::create('sync_queue', function (Blueprint $table) {
            $table->id();
            $table->string('table_name');
            $table->uuid('row_uuid');
            $table->string('action');          // create | update | delete
            $table->json('payload')->nullable();
            $table->timestamp('queued_at');
            $table->timestamp('synced_at')->nullable();
            $table->unsignedInteger('attempts')->default(0);
            $table->text('last_error')->nullable();

            $table->index(['synced_at', 'id']);
            $table->index('row_uuid');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('sync_queue');

        foreach (['expenses', 'categories'] as $table) {
            Schema::table($table, function (Blueprint $t) use ($table) {
                $t->dropUnique($table.'_uuid_unique');
                $t->dropColumn(['uuid', 'synced_at']);
            });
        }
    }
};
