<?php

use App\Models\Module;
use App\Models\Permission;
use App\Models\RoleModules;
use App\Models\RolePermission;
use Illuminate\Database\Migrations\Migration;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 1. Update quick_sms module link to /admin/sms_messages
        Module::where('name', 'quick_sms')
            ->orWhere('link', '/admin/quick_sms')
            ->update([
                'link' => '/admin/sms_messages',
            ]);

        // 2. Remove duplicate sms_messages module if quick_sms now points to /admin/sms_messages
        $duplicateSmsModule = Module::where('name', 'sms_messages')
            ->where('id', '!=', 17)
            ->first();

        if ($duplicateSmsModule) {
            Permission::where('module_id', $duplicateSmsModule->id)->delete();
            RoleModules::where('module_id', $duplicateSmsModule->id)->delete();
            $duplicateSmsModule->delete();
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Module::where('name', 'quick_sms')
            ->update([
                'link' => '/admin/quick_sms',
            ]);
    }
};
