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

#nullable disable

namespace JobTrackerApi.Migrations;

/// <summary>
/// Transfers creation ownership of the legacy SystemEmailSettings singleton from startup
/// reconciliation to the migration chain. Both statements are additive and preserve a table
/// created by an older MariaDB deployment.
/// </summary>
[DbContext(typeof(JobTrackerContext))]
[Migration("20260830120000_AdoptSystemEmailSettingsSchema")]
public sealed class AdoptSystemEmailSettingsSchema : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        if (ActiveProvider.Contains("MySql", StringComparison.OrdinalIgnoreCase))
        {
            migrationBuilder.Sql("""
                CREATE TABLE IF NOT EXISTS `SystemEmailSettings` (
                    `Id` int NOT NULL,
                    `Enabled` tinyint(1) NULL,
                    `SmtpHost` longtext NULL,
                    `SmtpPort` int NULL,
                    `SmtpUser` longtext NULL,
                    `SmtpPassword` longtext NULL,
                    `From` longtext NULL,
                    `FromName` longtext NULL,
                    `SmtpEnableSsl` tinyint(1) NULL,
                    `SmtpTimeoutMs` int NULL,
                    PRIMARY KEY (`Id`)
                ) CHARACTER SET=utf8mb4;
                """);
            return;
        }

        migrationBuilder.Sql("""
            CREATE TABLE IF NOT EXISTS "SystemEmailSettings" (
                "Id" INTEGER NOT NULL CONSTRAINT "PK_SystemEmailSettings" PRIMARY KEY,
                "Enabled" INTEGER NULL,
                "SmtpHost" TEXT NULL,
                "SmtpPort" INTEGER NULL,
                "SmtpUser" TEXT NULL,
                "SmtpPassword" TEXT NULL,
                "From" TEXT NULL,
                "FromName" TEXT NULL,
                "SmtpEnableSsl" INTEGER NULL,
                "SmtpTimeoutMs" INTEGER NULL
            );
            """);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        // Deliberately preserve the table: older deployments created it outside migrations, so a
        // downgrade cannot know whether this migration owns the existing data.
    }
}
