<?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::table('website_type', function (Blueprint $table): void {
            $table->string('site_title')->nullable()->after('scanner_domain');
            $table->unsignedBigInteger('favicon_id')->nullable()->after('footer_logo');

            $table->foreign('favicon_id')
                ->references('id')
                ->on('attachments')
                ->nullOnDelete();
        });

        Schema::table('tenants', function (Blueprint $table): void {
            $table->string('site_title')->nullable()->after('dominio');
            $table->unsignedBigInteger('favicon_id')->nullable()->after('footer_logo_id');

            $table->foreign('favicon_id')
                ->references('id')
                ->on('attachments')
                ->nullOnDelete();
        });

        DB::table('website_type')
            ->whereNull('site_title')
            ->update(['site_title' => DB::raw('nombre')]);
    }

    public function down(): void
    {
        Schema::table('tenants', function (Blueprint $table): void {
            if (Schema::getConnection()->getDriverName() !== 'sqlite') {
                $table->dropForeign(['favicon_id']);
            }

            $table->dropColumn(['site_title', 'favicon_id']);
        });

        Schema::table('website_type', function (Blueprint $table): void {
            if (Schema::getConnection()->getDriverName() !== 'sqlite') {
                $table->dropForeign(['favicon_id']);
            }

            $table->dropColumn(['site_title', 'favicon_id']);
        });
    }
};
