using System;
using JobTrackerApi.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace JobTrackerApi.Migrations;

/// <summary>
/// Moves append-only cover-letter revision history into migration ownership without replacing
/// manually edited or AI-approved document versions.
/// </summary>
[DbContext(typeof(JobTrackerContext))]
[Migration("20260830131000_AdoptCoverLetterVersionSchema")]
public sealed class AdoptCoverLetterVersionSchema : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        if (ActiveProvider.Contains("MySql", StringComparison.OrdinalIgnoreCase))
        {
            migrationBuilder.Sql("""
                CREATE TABLE IF NOT EXISTS `CoverLetterVersions` (
                    `Id` int NOT NULL AUTO_INCREMENT,
                    `OwnerUserId` varchar(255) NOT NULL,
                    `JobApplicationId` int NOT NULL,
                    `Version` int NOT NULL,
                    `Text` longtext NOT NULL,
                    `Source` varchar(32) NOT NULL,
                    `AiAction` varchar(32) NULL,
                    `CreatedAtUtc` datetime(6) NOT NULL,
                    PRIMARY KEY (`Id`),
                    CONSTRAINT `FK_CoverLetterVersions_JobApplications_JobApplicationId`
                        FOREIGN KEY (`JobApplicationId`) REFERENCES `JobApplications` (`Id`) ON DELETE CASCADE
                ) CHARACTER SET=utf8mb4;
                CREATE INDEX IF NOT EXISTS `IX_CoverLetterVersions_Owner_Job_Version`
                    ON `CoverLetterVersions` (`OwnerUserId`, `JobApplicationId`, `Version`);
                """);
            return;
        }

        migrationBuilder.Sql("""
            CREATE TABLE IF NOT EXISTS "CoverLetterVersions" (
                "Id" INTEGER NOT NULL CONSTRAINT "PK_CoverLetterVersions" PRIMARY KEY AUTOINCREMENT,
                "OwnerUserId" TEXT NOT NULL,
                "JobApplicationId" INTEGER NOT NULL,
                "Version" INTEGER NOT NULL,
                "Text" TEXT NOT NULL,
                "Source" TEXT NOT NULL,
                "AiAction" TEXT NULL,
                "CreatedAtUtc" TEXT NOT NULL,
                CONSTRAINT "FK_CoverLetterVersions_JobApplications_JobApplicationId"
                    FOREIGN KEY ("JobApplicationId") REFERENCES "JobApplications" ("Id") ON DELETE CASCADE
            );
            CREATE INDEX IF NOT EXISTS "IX_CoverLetterVersions_Owner_Job_Version"
                ON "CoverLetterVersions" ("OwnerUserId", "JobApplicationId", "Version");
            """);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        // Preserve recoverable document history created before migration ownership.
    }
}
