<?php

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::create('cash_sessions', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('branch_id')->constrained('branches');
            $table->foreignId('user_id')->constrained('users');
            $table->bigInteger('opening_balance')->default(0);
            $table->bigInteger('closing_balance')->nullable();
            $table->bigInteger('expected_balance')->nullable();
            $table->bigInteger('variance')->nullable();
            $table->bigInteger('total_cash_in')->default(0);
            $table->bigInteger('total_cash_out')->default(0);
            $table->integer('transactions_count')->default(0);
            $table->string('status', 20)->default('open');
            $table->timestamp('opened_at');
            $table->timestamp('closed_at')->nullable();
            $table->text('opening_notes')->nullable();
            $table->text('closing_notes')->nullable();
            $table->foreignId('closed_by')->nullable()->constrained('users');
            $table->jsonb('denominations')->nullable();
            $table->jsonb('metadata')->default('{}');
            $table->timestamps();

            $table->index(['academy_id', 'user_id', 'status']);
            $table->index(['branch_id', 'status']);
        });

        DB::statement("ALTER TABLE cash_sessions ADD CONSTRAINT cash_sessions_status_check CHECK (status IN ('open', 'closed', 'suspended'))");
    }

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