using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace TeleWave.Infrastructure.Migrations
{
    /// <inheritdoc />
    public partial class ShowPosterImage : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AlterColumn<string>(
                name: "OriginalName",
                table: "Shows",
                type: "character varying(256)",
                maxLength: 256,
                nullable: true,
                oldClrType: typeof(string),
                oldType: "text",
                oldNullable: true
            );

            migrationBuilder.AddColumn<Guid>(
                name: "PosterImageId",
                table: "Shows",
                type: "uuid",
                nullable: true
            );

            // Переносим существующие постеры шоу в общий реестр изображений: на каждый постер —
            // запись Images (Category=1 ShowPoster) с расширением из старого пути; файлы перекладывает
            // startup-шаг RelocateLegacyImagesAsync. Затем удаляем колонку PosterPath.
            migrationBuilder.Sql(
                """
                DO $$
                DECLARE r RECORD; img uuid;
                BEGIN
                  FOR r IN SELECT "Id", "PosterPath" FROM "Shows" WHERE "PosterPath" IS NOT NULL LOOP
                    img := gen_random_uuid();
                    INSERT INTO "Images" ("Id", "Category", "FileExtension", "OriginalFileName", "CreatedAt")
                    VALUES (img, 1, lower(coalesce(substring(r."PosterPath" from '\.[^.]*$'), '.jpg')), 'poster', now());
                    UPDATE "Shows" SET "PosterImageId" = img WHERE "Id" = r."Id";
                  END LOOP;
                END $$;
                """
            );

            migrationBuilder.DropColumn(name: "PosterPath", table: "Shows");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(name: "PosterImageId", table: "Shows");

            migrationBuilder.AlterColumn<string>(
                name: "OriginalName",
                table: "Shows",
                type: "text",
                nullable: true,
                oldClrType: typeof(string),
                oldType: "character varying(256)",
                oldMaxLength: 256,
                oldNullable: true
            );

            migrationBuilder.AddColumn<string>(
                name: "PosterPath",
                table: "Shows",
                type: "character varying(256)",
                maxLength: 256,
                nullable: true
            );
        }
    }
}
