<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('artworks') && Schema::hasTable('artwork_category')) {
            Schema::table('artwork_category', function (Blueprint $table) {
                $table->foreign('artwork_id')
                    ->references('id')
                    ->on('artworks')
                    ->cascadeOnDelete();
            });
        }
    }

    public function down(): void
    {
        if (Schema::hasTable('artwork_category')) {
            try {
                Schema::table('artwork_category', function (Blueprint $table) {
                    $table->dropForeign(['artwork_id']);
                });
            } catch (\Exception $e) {
                // Foreign key does not exist or cannot be dropped; ignore.
            }
        }
    }
};
