using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace PowderCoating.Infrastructure.Migrations
{
    /// <inheritdoc />
    public partial class ConvertEnumsToLookupTables : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            // ============================================================================
            // STEP 1: Add temporary columns to preserve enum values
            // ============================================================================

            migrationBuilder.AddColumn<int>(
                name: "OldStatus",
                table: "Jobs",
                type: "int",
                nullable: false,
                defaultValue: 0);

            migrationBuilder.AddColumn<int>(
                name: "OldPriority",
                table: "Jobs",
                type: "int",
                nullable: false,
                defaultValue: 0);

            migrationBuilder.AddColumn<int>(
                name: "OldStatus",
                table: "Quotes",
                type: "int",
                nullable: false,
                defaultValue: 0);

            migrationBuilder.AddColumn<int>(
                name: "OldFromStatus",
                table: "JobStatusHistory",
                type: "int",
                nullable: false,
                defaultValue: 0);

            migrationBuilder.AddColumn<int>(
                name: "OldToStatus",
                table: "JobStatusHistory",
                type: "int",
                nullable: false,
                defaultValue: 0);

            // Copy existing enum values to temp columns
            migrationBuilder.Sql("UPDATE Jobs SET OldStatus = Status, OldPriority = Priority");
            migrationBuilder.Sql("UPDATE Quotes SET OldStatus = Status");
            migrationBuilder.Sql("UPDATE JobStatusHistory SET OldFromStatus = FromStatus, OldToStatus = ToStatus");

            // ============================================================================
            // STEP 2: Create lookup tables
            // ============================================================================

            migrationBuilder.CreateTable(
                name: "JobStatusLookups",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    StatusCode = table.Column<string>(type: "nvarchar(450)", nullable: false),
                    DisplayName = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    DisplayOrder = table.Column<int>(type: "int", nullable: false),
                    ColorClass = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    IconClass = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    IsActive = table.Column<bool>(type: "bit", nullable: false),
                    IsSystemDefined = table.Column<bool>(type: "bit", nullable: false),
                    IsTerminalStatus = table.Column<bool>(type: "bit", nullable: false),
                    IsWorkInProgressStatus = table.Column<bool>(type: "bit", nullable: false),
                    Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    WorkflowCategory = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    CompanyId = table.Column<int>(type: "int", nullable: false),
                    CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    IsDeleted = table.Column<bool>(type: "bit", nullable: false),
                    DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_JobStatusLookups", x => x.Id);
                    table.ForeignKey(
                        name: "FK_JobStatusLookups_Companies_CompanyId",
                        column: x => x.CompanyId,
                        principalTable: "Companies",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateTable(
                name: "JobPriorityLookups",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    PriorityCode = table.Column<string>(type: "nvarchar(450)", nullable: false),
                    DisplayName = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    DisplayOrder = table.Column<int>(type: "int", nullable: false),
                    ColorClass = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    IconClass = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    IsActive = table.Column<bool>(type: "bit", nullable: false),
                    IsSystemDefined = table.Column<bool>(type: "bit", nullable: false),
                    Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    CompanyId = table.Column<int>(type: "int", nullable: false),
                    CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    IsDeleted = table.Column<bool>(type: "bit", nullable: false),
                    DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_JobPriorityLookups", x => x.Id);
                    table.ForeignKey(
                        name: "FK_JobPriorityLookups_Companies_CompanyId",
                        column: x => x.CompanyId,
                        principalTable: "Companies",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateTable(
                name: "QuoteStatusLookups",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    StatusCode = table.Column<string>(type: "nvarchar(450)", nullable: false),
                    DisplayName = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    DisplayOrder = table.Column<int>(type: "int", nullable: false),
                    ColorClass = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    IconClass = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    IsActive = table.Column<bool>(type: "bit", nullable: false),
                    IsSystemDefined = table.Column<bool>(type: "bit", nullable: false),
                    IsApprovedStatus = table.Column<bool>(type: "bit", nullable: false),
                    IsConvertedStatus = table.Column<bool>(type: "bit", nullable: false),
                    IsDraftStatus = table.Column<bool>(type: "bit", nullable: false),
                    Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    CompanyId = table.Column<int>(type: "int", nullable: false),
                    CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
                    UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    IsDeleted = table.Column<bool>(type: "bit", nullable: false),
                    DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
                    DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_QuoteStatusLookups", x => x.Id);
                    table.ForeignKey(
                        name: "FK_QuoteStatusLookups_Companies_CompanyId",
                        column: x => x.CompanyId,
                        principalTable: "Companies",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            // ============================================================================
            // STEP 3: Seed lookup data for ALL existing companies
            // ============================================================================

            // Insert Job Status Lookups (16 statuses per company)
            migrationBuilder.Sql(@"
                INSERT INTO JobStatusLookups (StatusCode, DisplayName, DisplayOrder, ColorClass, IconClass, IsActive, IsSystemDefined, IsTerminalStatus, IsWorkInProgressStatus, Description, WorkflowCategory, CompanyId, CreatedAt, IsDeleted)
                SELECT
                    s.StatusCode, s.DisplayName, s.DisplayOrder, s.ColorClass, s.IconClass, s.IsActive, s.IsSystemDefined, s.IsTerminalStatus, s.IsWorkInProgressStatus, s.Description, s.WorkflowCategory, c.Id, GETUTCDATE(), 0
                FROM Companies c
                CROSS JOIN (VALUES
                    ('PENDING', 'Pending', 1, 'secondary', 'bi-clock', 1, 1, 0, 0, 'Job is pending approval or scheduling', 'Pre-Production'),
                    ('QUOTED', 'Quoted', 2, 'info', 'bi-file-earmark-text', 1, 0, 0, 0, 'Quote has been generated', 'Pre-Production'),
                    ('APPROVED', 'Approved', 3, 'primary', 'bi-check-circle', 1, 0, 0, 0, 'Job has been approved', 'Pre-Production'),
                    ('IN_PREPARATION', 'In Preparation', 4, 'warning', 'bi-tools', 1, 0, 0, 1, 'Job is being prepared', 'Production'),
                    ('SANDBLASTING', 'Sandblasting', 5, 'warning', 'bi-hurricane', 1, 0, 0, 1, 'Surface preparation in progress', 'Production'),
                    ('MASKING_TAPING', 'Masking/Taping', 6, 'warning', 'bi-scissors', 1, 0, 0, 1, 'Masking areas for coating', 'Production'),
                    ('CLEANING', 'Cleaning', 7, 'warning', 'bi-droplet', 1, 0, 0, 1, 'Pre-coat cleaning', 'Production'),
                    ('IN_OVEN', 'In Oven', 8, 'warning', 'bi-thermometer-half', 1, 0, 0, 1, 'Pre-heating in oven', 'Production'),
                    ('COATING', 'Coating', 9, 'warning', 'bi-paint-bucket', 1, 0, 0, 1, 'Applying powder coating', 'Production'),
                    ('CURING', 'Curing', 10, 'warning', 'bi-thermometer-sun', 1, 0, 0, 1, 'Heat curing the coating', 'Production'),
                    ('QUALITY_CHECK', 'Quality Check', 11, 'info', 'bi-search', 1, 0, 0, 1, 'Quality inspection', 'Production'),
                    ('COMPLETED', 'Completed', 12, 'success', 'bi-check-all', 1, 1, 1, 0, 'Job is completed', 'Post-Production'),
                    ('READY_FOR_PICKUP', 'Ready for Pickup', 13, 'success', 'bi-box-seam', 1, 0, 0, 0, 'Ready for customer pickup', 'Post-Production'),
                    ('DELIVERED', 'Delivered', 14, 'success', 'bi-truck', 1, 0, 1, 0, 'Delivered to customer', 'Post-Production'),
                    ('ON_HOLD', 'On Hold', 15, 'dark', 'bi-pause-circle', 1, 0, 0, 0, 'Job is temporarily on hold', 'Other'),
                    ('CANCELLED', 'Cancelled', 16, 'danger', 'bi-x-circle', 1, 1, 1, 0, 'Job has been cancelled', 'Other')
                ) AS s(StatusCode, DisplayName, DisplayOrder, ColorClass, IconClass, IsActive, IsSystemDefined, IsTerminalStatus, IsWorkInProgressStatus, Description, WorkflowCategory)
                WHERE c.IsDeleted = 0
            ");

            // Insert Job Priority Lookups (5 priorities per company)
            migrationBuilder.Sql(@"
                INSERT INTO JobPriorityLookups (PriorityCode, DisplayName, DisplayOrder, ColorClass, IconClass, IsActive, IsSystemDefined, Description, CompanyId, CreatedAt, IsDeleted)
                SELECT
                    p.PriorityCode, p.DisplayName, p.DisplayOrder, p.ColorClass, p.IconClass, p.IsActive, p.IsSystemDefined, p.Description, c.Id, GETUTCDATE(), 0
                FROM Companies c
                CROSS JOIN (VALUES
                    ('LOW', 'Low', 1, 'secondary', 'bi-arrow-down', 1, 0, 'Low priority job'),
                    ('NORMAL', 'Normal', 2, 'primary', NULL, 1, 1, 'Standard priority job'),
                    ('HIGH', 'High', 3, 'info', 'bi-arrow-up', 1, 0, 'High priority job'),
                    ('URGENT', 'Urgent', 4, 'warning', 'bi-exclamation-triangle', 1, 0, 'Urgent job - expedited processing'),
                    ('RUSH', 'Rush', 5, 'danger', 'bi-lightning', 1, 0, 'Rush job - immediate processing required')
                ) AS p(PriorityCode, DisplayName, DisplayOrder, ColorClass, IconClass, IsActive, IsSystemDefined, Description)
                WHERE c.IsDeleted = 0
            ");

            // Insert Quote Status Lookups (7 statuses per company)
            migrationBuilder.Sql(@"
                INSERT INTO QuoteStatusLookups (StatusCode, DisplayName, DisplayOrder, ColorClass, IconClass, IsActive, IsSystemDefined, IsApprovedStatus, IsConvertedStatus, IsDraftStatus, Description, CompanyId, CreatedAt, IsDeleted)
                SELECT
                    qs.StatusCode, qs.DisplayName, qs.DisplayOrder, qs.ColorClass, qs.IconClass, qs.IsActive, qs.IsSystemDefined, qs.IsApprovedStatus, qs.IsConvertedStatus, qs.IsDraftStatus, qs.Description, c.Id, GETUTCDATE(), 0
                FROM Companies c
                CROSS JOIN (VALUES
                    ('DRAFT', 'Draft', 1, 'secondary', 'bi-pencil', 1, 1, 0, 0, 1, 'Quote is being drafted'),
                    ('SENT', 'Sent', 2, 'info', 'bi-send', 1, 0, 0, 0, 0, 'Quote has been sent to customer'),
                    ('APPROVED', 'Approved', 3, 'success', 'bi-check-circle', 1, 1, 1, 0, 0, 'Quote has been approved by customer'),
                    ('REJECTED', 'Rejected', 4, 'danger', 'bi-x-circle', 1, 0, 0, 0, 0, 'Quote was rejected by customer'),
                    ('EXPIRED', 'Expired', 5, 'dark', 'bi-clock-history', 1, 0, 0, 0, 0, 'Quote has expired'),
                    ('CONVERTED', 'Converted', 6, 'primary', 'bi-arrow-right-circle', 1, 1, 0, 1, 0, 'Quote has been converted to job'),
                    ('REVISED', 'Revised', 7, 'warning', 'bi-arrow-clockwise', 1, 0, 0, 0, 0, 'Quote is being revised')
                ) AS qs(StatusCode, DisplayName, DisplayOrder, ColorClass, IconClass, IsActive, IsSystemDefined, IsApprovedStatus, IsConvertedStatus, IsDraftStatus, Description)
                WHERE c.IsDeleted = 0
            ");

            // ============================================================================
            // STEP 4: Rename and add new FK columns
            // ============================================================================

            migrationBuilder.RenameColumn(
                name: "Status",
                table: "Jobs",
                newName: "JobStatusId_OLD");

            migrationBuilder.RenameColumn(
                name: "Priority",
                table: "Jobs",
                newName: "JobPriorityId_OLD");

            migrationBuilder.RenameColumn(
                name: "Status",
                table: "Quotes",
                newName: "QuoteStatusId_OLD");

            migrationBuilder.RenameColumn(
                name: "FromStatus",
                table: "JobStatusHistory",
                newName: "FromStatusId_OLD");

            migrationBuilder.RenameColumn(
                name: "ToStatus",
                table: "JobStatusHistory",
                newName: "ToStatusId_OLD");

            // Add new FK columns (nullable initially)
            migrationBuilder.AddColumn<int>(
                name: "JobStatusId",
                table: "Jobs",
                type: "int",
                nullable: true);

            migrationBuilder.AddColumn<int>(
                name: "JobPriorityId",
                table: "Jobs",
                type: "int",
                nullable: true);

            migrationBuilder.AddColumn<int>(
                name: "QuoteStatusId",
                table: "Quotes",
                type: "int",
                nullable: true);

            migrationBuilder.AddColumn<int>(
                name: "FromStatusId",
                table: "JobStatusHistory",
                type: "int",
                nullable: true);

            migrationBuilder.AddColumn<int>(
                name: "ToStatusId",
                table: "JobStatusHistory",
                type: "int",
                nullable: true);

            // ============================================================================
            // STEP 5: Map enum values to lookup IDs
            // ============================================================================

            // Map Job Status: enum int (0-15) -> lookup ID
            // Enum: Pending=0, Quoted=1, Approved=2, InPreparation=3, Sandblasting=4, MaskingTaping=5,
            //       Cleaning=6, InOven=7, Coating=8, Curing=9, QualityCheck=10, Completed=11,
            //       ReadyForPickup=12, Delivered=13, OnHold=14, Cancelled=15
            migrationBuilder.Sql(@"
                UPDATE j
                SET j.JobStatusId = s.Id
                FROM Jobs j
                INNER JOIN JobStatusLookups s ON j.CompanyId = s.CompanyId
                WHERE s.StatusCode = CASE j.OldStatus
                    WHEN 0 THEN 'PENDING'
                    WHEN 1 THEN 'QUOTED'
                    WHEN 2 THEN 'APPROVED'
                    WHEN 3 THEN 'IN_PREPARATION'
                    WHEN 4 THEN 'SANDBLASTING'
                    WHEN 5 THEN 'MASKING_TAPING'
                    WHEN 6 THEN 'CLEANING'
                    WHEN 7 THEN 'IN_OVEN'
                    WHEN 8 THEN 'COATING'
                    WHEN 9 THEN 'CURING'
                    WHEN 10 THEN 'QUALITY_CHECK'
                    WHEN 11 THEN 'COMPLETED'
                    WHEN 12 THEN 'READY_FOR_PICKUP'
                    WHEN 13 THEN 'DELIVERED'
                    WHEN 14 THEN 'ON_HOLD'
                    WHEN 15 THEN 'CANCELLED'
                END
            ");

            // Map Job Priority: enum int (0-4) -> lookup ID
            // Enum: Low=0, Normal=1, High=2, Urgent=3, Rush=4
            migrationBuilder.Sql(@"
                UPDATE j
                SET j.JobPriorityId = p.Id
                FROM Jobs j
                INNER JOIN JobPriorityLookups p ON j.CompanyId = p.CompanyId
                WHERE p.PriorityCode = CASE j.OldPriority
                    WHEN 0 THEN 'LOW'
                    WHEN 1 THEN 'NORMAL'
                    WHEN 2 THEN 'HIGH'
                    WHEN 3 THEN 'URGENT'
                    WHEN 4 THEN 'RUSH'
                END
            ");

            // Map Quote Status: enum int (0-6) -> lookup ID
            // Enum: Draft=0, Sent=1, Approved=2, Rejected=3, Expired=4, Converted=5, Revised=6
            migrationBuilder.Sql(@"
                UPDATE q
                SET q.QuoteStatusId = s.Id
                FROM Quotes q
                INNER JOIN QuoteStatusLookups s ON q.CompanyId = s.CompanyId
                WHERE s.StatusCode = CASE q.OldStatus
                    WHEN 0 THEN 'DRAFT'
                    WHEN 1 THEN 'SENT'
                    WHEN 2 THEN 'APPROVED'
                    WHEN 3 THEN 'REJECTED'
                    WHEN 4 THEN 'EXPIRED'
                    WHEN 5 THEN 'CONVERTED'
                    WHEN 6 THEN 'REVISED'
                END
            ");

            // Map JobStatusHistory FromStatus and ToStatus
            migrationBuilder.Sql(@"
                UPDATE h
                SET h.FromStatusId = s.Id
                FROM JobStatusHistory h
                INNER JOIN Jobs j ON h.JobId = j.Id
                INNER JOIN JobStatusLookups s ON j.CompanyId = s.CompanyId
                WHERE s.StatusCode = CASE h.OldFromStatus
                    WHEN 0 THEN 'PENDING'
                    WHEN 1 THEN 'QUOTED'
                    WHEN 2 THEN 'APPROVED'
                    WHEN 3 THEN 'IN_PREPARATION'
                    WHEN 4 THEN 'SANDBLASTING'
                    WHEN 5 THEN 'MASKING_TAPING'
                    WHEN 6 THEN 'CLEANING'
                    WHEN 7 THEN 'IN_OVEN'
                    WHEN 8 THEN 'COATING'
                    WHEN 9 THEN 'CURING'
                    WHEN 10 THEN 'QUALITY_CHECK'
                    WHEN 11 THEN 'COMPLETED'
                    WHEN 12 THEN 'READY_FOR_PICKUP'
                    WHEN 13 THEN 'DELIVERED'
                    WHEN 14 THEN 'ON_HOLD'
                    WHEN 15 THEN 'CANCELLED'
                END
            ");

            migrationBuilder.Sql(@"
                UPDATE h
                SET h.ToStatusId = s.Id
                FROM JobStatusHistory h
                INNER JOIN Jobs j ON h.JobId = j.Id
                INNER JOIN JobStatusLookups s ON j.CompanyId = s.CompanyId
                WHERE s.StatusCode = CASE h.OldToStatus
                    WHEN 0 THEN 'PENDING'
                    WHEN 1 THEN 'QUOTED'
                    WHEN 2 THEN 'APPROVED'
                    WHEN 3 THEN 'IN_PREPARATION'
                    WHEN 4 THEN 'SANDBLASTING'
                    WHEN 5 THEN 'MASKING_TAPING'
                    WHEN 6 THEN 'CLEANING'
                    WHEN 7 THEN 'IN_OVEN'
                    WHEN 8 THEN 'COATING'
                    WHEN 9 THEN 'CURING'
                    WHEN 10 THEN 'QUALITY_CHECK'
                    WHEN 11 THEN 'COMPLETED'
                    WHEN 12 THEN 'READY_FOR_PICKUP'
                    WHEN 13 THEN 'DELIVERED'
                    WHEN 14 THEN 'ON_HOLD'
                    WHEN 15 THEN 'CANCELLED'
                END
            ");

            // ============================================================================
            // STEP 6: Make FK columns NOT NULL
            // ============================================================================

            migrationBuilder.AlterColumn<int>(
                name: "JobStatusId",
                table: "Jobs",
                type: "int",
                nullable: false,
                oldClrType: typeof(int),
                oldType: "int",
                oldNullable: true);

            migrationBuilder.AlterColumn<int>(
                name: "JobPriorityId",
                table: "Jobs",
                type: "int",
                nullable: false,
                oldClrType: typeof(int),
                oldType: "int",
                oldNullable: true);

            migrationBuilder.AlterColumn<int>(
                name: "QuoteStatusId",
                table: "Quotes",
                type: "int",
                nullable: false,
                oldClrType: typeof(int),
                oldType: "int",
                oldNullable: true);

            migrationBuilder.AlterColumn<int>(
                name: "FromStatusId",
                table: "JobStatusHistory",
                type: "int",
                nullable: false,
                oldClrType: typeof(int),
                oldType: "int",
                oldNullable: true);

            migrationBuilder.AlterColumn<int>(
                name: "ToStatusId",
                table: "JobStatusHistory",
                type: "int",
                nullable: false,
                oldClrType: typeof(int),
                oldType: "int",
                oldNullable: true);

            // ============================================================================
            // STEP 7: Create indexes and foreign keys
            // ============================================================================

            migrationBuilder.CreateIndex(
                name: "IX_Jobs_JobStatusId",
                table: "Jobs",
                column: "JobStatusId");

            migrationBuilder.CreateIndex(
                name: "IX_Jobs_JobPriorityId",
                table: "Jobs",
                column: "JobPriorityId");

            migrationBuilder.CreateIndex(
                name: "IX_Quotes_QuoteStatusId",
                table: "Quotes",
                column: "QuoteStatusId");

            migrationBuilder.CreateIndex(
                name: "IX_JobStatusHistory_FromStatusId",
                table: "JobStatusHistory",
                column: "FromStatusId");

            migrationBuilder.CreateIndex(
                name: "IX_JobStatusHistory_ToStatusId",
                table: "JobStatusHistory",
                column: "ToStatusId");

            migrationBuilder.CreateIndex(
                name: "IX_JobStatusLookups_CompanyId",
                table: "JobStatusLookups",
                column: "CompanyId");

            migrationBuilder.CreateIndex(
                name: "IX_JobStatusLookups_CompanyId_StatusCode",
                table: "JobStatusLookups",
                columns: new[] { "CompanyId", "StatusCode" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_JobPriorityLookups_CompanyId",
                table: "JobPriorityLookups",
                column: "CompanyId");

            migrationBuilder.CreateIndex(
                name: "IX_JobPriorityLookups_CompanyId_PriorityCode",
                table: "JobPriorityLookups",
                columns: new[] { "CompanyId", "PriorityCode" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_QuoteStatusLookups_CompanyId",
                table: "QuoteStatusLookups",
                column: "CompanyId");

            migrationBuilder.CreateIndex(
                name: "IX_QuoteStatusLookups_CompanyId_StatusCode",
                table: "QuoteStatusLookups",
                columns: new[] { "CompanyId", "StatusCode" },
                unique: true);

            migrationBuilder.AddForeignKey(
                name: "FK_Jobs_JobStatusLookups_JobStatusId",
                table: "Jobs",
                column: "JobStatusId",
                principalTable: "JobStatusLookups",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);

            migrationBuilder.AddForeignKey(
                name: "FK_Jobs_JobPriorityLookups_JobPriorityId",
                table: "Jobs",
                column: "JobPriorityId",
                principalTable: "JobPriorityLookups",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);

            migrationBuilder.AddForeignKey(
                name: "FK_Quotes_QuoteStatusLookups_QuoteStatusId",
                table: "Quotes",
                column: "QuoteStatusId",
                principalTable: "QuoteStatusLookups",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);

            migrationBuilder.AddForeignKey(
                name: "FK_JobStatusHistory_JobStatusLookups_FromStatusId",
                table: "JobStatusHistory",
                column: "FromStatusId",
                principalTable: "JobStatusLookups",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);

            migrationBuilder.AddForeignKey(
                name: "FK_JobStatusHistory_JobStatusLookups_ToStatusId",
                table: "JobStatusHistory",
                column: "ToStatusId",
                principalTable: "JobStatusLookups",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);

            // ============================================================================
            // STEP 8: Drop old columns and temp columns
            // ============================================================================

            migrationBuilder.DropColumn(name: "OldStatus", table: "Jobs");
            migrationBuilder.DropColumn(name: "OldPriority", table: "Jobs");
            migrationBuilder.DropColumn(name: "OldStatus", table: "Quotes");
            migrationBuilder.DropColumn(name: "OldFromStatus", table: "JobStatusHistory");
            migrationBuilder.DropColumn(name: "OldToStatus", table: "JobStatusHistory");
            migrationBuilder.DropColumn(name: "JobStatusId_OLD", table: "Jobs");
            migrationBuilder.DropColumn(name: "JobPriorityId_OLD", table: "Jobs");
            migrationBuilder.DropColumn(name: "QuoteStatusId_OLD", table: "Quotes");
            migrationBuilder.DropColumn(name: "FromStatusId_OLD", table: "JobStatusHistory");
            migrationBuilder.DropColumn(name: "ToStatusId_OLD", table: "JobStatusHistory");

            // Update PricingTiers seed data timestamps
            migrationBuilder.UpdateData(
                table: "PricingTiers",
                keyColumn: "Id",
                keyValue: 1,
                column: "CreatedAt",
                value: new DateTime(2026, 2, 13, 18, 39, 9, 909, DateTimeKind.Utc).AddTicks(1116));

            migrationBuilder.UpdateData(
                table: "PricingTiers",
                keyColumn: "Id",
                keyValue: 2,
                column: "CreatedAt",
                value: new DateTime(2026, 2, 13, 18, 39, 9, 909, DateTimeKind.Utc).AddTicks(1124));

            migrationBuilder.UpdateData(
                table: "PricingTiers",
                keyColumn: "Id",
                keyValue: 3,
                column: "CreatedAt",
                value: new DateTime(2026, 2, 13, 18, 39, 9, 909, DateTimeKind.Utc).AddTicks(1127));
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            // Drop foreign keys
            migrationBuilder.DropForeignKey(name: "FK_Jobs_JobStatusLookups_JobStatusId", table: "Jobs");
            migrationBuilder.DropForeignKey(name: "FK_Jobs_JobPriorityLookups_JobPriorityId", table: "Jobs");
            migrationBuilder.DropForeignKey(name: "FK_Quotes_QuoteStatusLookups_QuoteStatusId", table: "Quotes");
            migrationBuilder.DropForeignKey(name: "FK_JobStatusHistory_JobStatusLookups_FromStatusId", table: "JobStatusHistory");
            migrationBuilder.DropForeignKey(name: "FK_JobStatusHistory_JobStatusLookups_ToStatusId", table: "JobStatusHistory");

            // Drop indexes
            migrationBuilder.DropIndex(name: "IX_Jobs_JobStatusId", table: "Jobs");
            migrationBuilder.DropIndex(name: "IX_Jobs_JobPriorityId", table: "Jobs");
            migrationBuilder.DropIndex(name: "IX_Quotes_QuoteStatusId", table: "Quotes");
            migrationBuilder.DropIndex(name: "IX_JobStatusHistory_FromStatusId", table: "JobStatusHistory");
            migrationBuilder.DropIndex(name: "IX_JobStatusHistory_ToStatusId", table: "JobStatusHistory");

            // Drop lookup tables
            migrationBuilder.DropTable(name: "JobStatusLookups");
            migrationBuilder.DropTable(name: "JobPriorityLookups");
            migrationBuilder.DropTable(name: "QuoteStatusLookups");

            // Rename columns back to enum names
            migrationBuilder.RenameColumn(name: "JobStatusId", table: "Jobs", newName: "Status");
            migrationBuilder.RenameColumn(name: "JobPriorityId", table: "Jobs", newName: "Priority");
            migrationBuilder.RenameColumn(name: "QuoteStatusId", table: "Quotes", newName: "Status");
            migrationBuilder.RenameColumn(name: "FromStatusId", table: "JobStatusHistory", newName: "FromStatus");
            migrationBuilder.RenameColumn(name: "ToStatusId", table: "JobStatusHistory", newName: "ToStatus");

            // Update PricingTiers timestamps
            migrationBuilder.UpdateData(
                table: "PricingTiers",
                keyColumn: "Id",
                keyValue: 1,
                column: "CreatedAt",
                value: new DateTime(2026, 2, 13, 16, 25, 10, 85, DateTimeKind.Utc).AddTicks(5660));

            migrationBuilder.UpdateData(
                table: "PricingTiers",
                keyColumn: "Id",
                keyValue: 2,
                column: "CreatedAt",
                value: new DateTime(2026, 2, 13, 16, 25, 10, 85, DateTimeKind.Utc).AddTicks(5668));

            migrationBuilder.UpdateData(
                table: "PricingTiers",
                keyColumn: "Id",
                keyValue: 3,
                column: "CreatedAt",
                value: new DateTime(2026, 2, 13, 16, 25, 10, 85, DateTimeKind.Utc).AddTicks(5669));
        }
    }
}
