<?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::dropIfExists('replenishment_rules');

        $permissionIds = DB::table('permissions')
            ->where('name', 'replenishment.manage')
            ->pluck('id');

        if ($permissionIds->isNotEmpty()) {
            DB::table('role_has_permissions')
                ->whereIn('permission_id', $permissionIds)
                ->delete();

            if (Schema::hasTable('model_has_permissions')) {
                DB::table('model_has_permissions')
                    ->whereIn('permission_id', $permissionIds)
                    ->delete();
            }

            DB::table('permissions')
                ->whereIn('id', $permissionIds)
                ->delete();
        }
    }

    public function down(): void
    {
        if (! Schema::hasTable('replenishment_rules')) {
            Schema::create('replenishment_rules', function (Blueprint $table) {
                $table->id();
                $table->foreignId('store_location_id')->constrained('locations')->cascadeOnDelete();
                $table->foreignId('warehouse_location_id')->constrained('locations')->cascadeOnDelete();
                $table->foreignId('product_id')->nullable()->constrained('products')->nullOnDelete();
                $table->integer('min_qty')->default(0);
                $table->integer('max_qty')->default(0);
                $table->integer('reorder_qty')->default(0);
                $table->boolean('is_active')->default(true);
                $table->timestamps();

                $table->index(['store_location_id', 'is_active']);
            });
        }

        $exists = DB::table('permissions')
            ->where('name', 'replenishment.manage')
            ->where('guard_name', 'web')
            ->exists();

        if (! $exists) {
            DB::table('permissions')->insert([
                'name' => 'replenishment.manage',
                'guard_name' => 'web',
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }
};
