<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 1. Clean up duplicate products (keep only the first one based on ID for each lowercase name)
        $duplicates = DB::select("
            SELECT id FROM products p1
            WHERE EXISTS (
                SELECT 1 FROM products p2 
                WHERE LOWER(p1.name) = LOWER(p2.name) 
                AND p1.id > p2.id
            )
        ");

        $duplicateIds = array_column($duplicates, 'id');
        
        if (!empty($duplicateIds)) {
            // Optional: Reassign purchase/sales references if necessary, or just delete.
            // Since this is a hard shift, we will just delete the duplicates.
            DB::table('products')->whereIn('id', $duplicateIds)->delete();
        }

        // 2. Modify the table schema
        Schema::table('products', function (Blueprint $table) {
            $table->dropColumn('branch');
            // Adding unique constraint to name to prevent future duplicates at database level
            // Note: because collation might differ, we'll keep the application-level validation too,
            // but this adds a hard layer of protection.
            $table->unique('name');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('products', function (Blueprint $table) {
            $table->dropUnique(['name']);
            $table->string('branch')->nullable();
        });
    }
};
