<?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
    {
        if (! Schema::hasTable('story_tags')) {
            Schema::create('story_tags', function (Blueprint $table): void {
                $table->id();
                $table->string('name', 120)->unique();
                $table->string('slug', 140)->unique();
                $table->timestamps();
            });
        }

        if (! Schema::hasTable('relation_story_tags')) {
            Schema::create('relation_story_tags', function (Blueprint $table): void {
                $table->foreignId('story_id')->constrained('stories')->cascadeOnDelete();
                $table->foreignId('tag_id')->constrained('story_tags')->cascadeOnDelete();
                $table->primary(['story_id', 'tag_id']);
            });
        }

        if (Schema::hasTable('stories_tags')) {
            $legacyTags = DB::table('stories_tags')->get();

            foreach ($legacyTags as $legacyTag) {
                DB::table('story_tags')->insertOrIgnore([
                    'name' => (string) $legacyTag->name,
                    'slug' => (string) $legacyTag->slug,
                    'created_at' => $legacyTag->created_at ?? now(),
                    'updated_at' => $legacyTag->updated_at ?? now(),
                ]);
            }
        }

        if (Schema::hasTable('stories_tag_relation')) {
            $legacyRelation = DB::table('stories_tag_relation as relation')
                ->join('stories_tags as legacy_tag', 'legacy_tag.id', '=', 'relation.tag_id')
                ->join('story_tags as new_tag', 'new_tag.slug', '=', 'legacy_tag.slug')
                ->get(['relation.story_id', 'new_tag.id as tag_id']);

            foreach ($legacyRelation as $pair) {
                DB::table('relation_story_tags')->insertOrIgnore([
                    'story_id' => (int) $pair->story_id,
                    'tag_id' => (int) $pair->tag_id,
                ]);
            }
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('relation_story_tags');
        Schema::dropIfExists('story_tags');
    }
};
