<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('batch_kpi_snapshots', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('batch_id')->constrained('batches')->cascadeOnDelete();
            $table->foreignId('tank_id')->constrained('tanks')->cascadeOnDelete();
            $table->date('snapshot_date');
            $table->unsignedInteger('fish_alive')->default(0);
            $table->decimal('avg_weight_g', 10, 2)->default(0);
            $table->decimal('biomass_kg', 12, 2)->default(0);
            $table->decimal('total_cost_crc', 14, 2)->default(0);
            $table->decimal('cost_per_kg_crc', 14, 2)->default(0);
            $table->decimal('projected_revenue_crc', 14, 2)->default(0);
            $table->decimal('projected_margin_crc', 14, 2)->default(0);
            $table->decimal('margin_per_kg_crc', 14, 2)->default(0);
            $table->decimal('break_even_weight_g', 10, 2)->default(0);
            $table->unsignedInteger('days_to_target_estimated')->nullable();
            $table->string('status', 20)->default('HEALTHY');
            $table->decimal('growth_rate_g_per_day', 10, 2)->default(0);
            $table->decimal('mortality_rate_pct', 8, 2)->default(0);
            $table->unsignedInteger('hidden_loss_fish')->default(0);
            $table->decimal('hidden_loss_biomass_kg', 12, 2)->default(0);
            $table->decimal('recommended_feed_g', 12, 2)->default(0);
            $table->decimal('actual_feed_g', 12, 2)->default(0);
            $table->decimal('feed_variance_g', 12, 2)->default(0);
            $table->decimal('density_fish_m3', 12, 2)->nullable();
            $table->decimal('density_biomass_kg_m3', 12, 2)->nullable();
            $table->timestamps();

            $table->unique(['batch_id', 'snapshot_date']);
            $table->index(['user_id', 'snapshot_date']);
            $table->index(['tank_id', 'snapshot_date']);
        });
    }

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