<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use App\Models\Inventory;
use App\Models\InventoryTransaction;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Get all inventories that don't have any transactions
        $inventoriesWithoutTransactions = Inventory::whereDoesntHave('transactions')->get();

        foreach ($inventoriesWithoutTransactions as $inventory) {
            // Create an "In" transaction for existing inventory
            InventoryTransaction::create([
                'inventory_id' => $inventory->id,
                'type' => 'in',
                'quantity' => $inventory->quantity ?? 0,
                'unit_price' => $inventory->unit_price ?? 0,
                'total_amount' => ($inventory->unit_price ?? 0) * ($inventory->quantity ?? 0),
                'reference_type' => 'addition',
                'reference_id' => $inventory->id,
                'batch_id' => $inventory->batch_id ?? null,
                'branch_id' => $inventory->branch_id,
                'restaurant_id' => $inventory->restaurant_id,
                'notes' => "Initial inventory addition for {$inventory->item_name}",
                'created_by' => $inventory->created_by ?? null,
                'created_at' => $inventory->created_at ?? now(),
                'updated_at' => $inventory->updated_at ?? now(),
            ]);

            // Update last_transaction_at
            $inventory->update(['last_transaction_at' => $inventory->created_at ?? now()]);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Find all "In" transactions that were created for existing inventories
        // (identified by reference_type = 'addition' and created_at matching inventory created_at)
        $transactionsToDelete = InventoryTransaction::where('reference_type', 'addition')
            ->where('type', 'in')
            ->whereHas('inventory', function($query) {
                $query->whereColumn('inventories.created_at', 'inventory_transactions.created_at');
            })
            ->get();

        foreach ($transactionsToDelete as $transaction) {
            $transaction->delete();
        }
    }
};
