using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using foodmarket.Infrastructure.Persistence;

#nullable disable

namespace foodmarket.Infrastructure.Persistence.Migrations
{
    /// <summary>Двухступенчатое удаление сотрудника: добавлены IsDeleted и
    /// DeletedAt. Ранее было только IsActive=false (увольнение); теперь:
    ///   IsActive=true                            — активный
    ///   IsActive=false  + FiredAt                — уволен
    ///   IsActive=false  + IsDeleted=true + DeletedAt — soft-deleted
    /// Физически Employee никогда не удаляем (FK из retail_sales, supplies).</summary>
    [DbContext(typeof(AppDbContext))]
    [Migration("20260506000000_Phase5a_EmployeeSoftDelete")]
    public partial class Phase5a_EmployeeSoftDelete : Migration
    {
        protected override void Up(MigrationBuilder b)
        {
            // Идемпотентно (см. CLAUDE memory feedback_ef_migrations): на чистой
            // dev-БД нужен AddColumn, на стейдже миграция могла быть применена
            // вручную через SQL — повторный AddColumn упадёт.
            b.Sql(@"
                DO $$
                BEGIN
                    IF NOT EXISTS (SELECT 1 FROM information_schema.columns
                                   WHERE table_schema='public' AND table_name='employees'
                                   AND column_name='IsDeleted') THEN
                        ALTER TABLE public.employees
                            ADD COLUMN ""IsDeleted"" boolean NOT NULL DEFAULT false;
                    END IF;
                    IF NOT EXISTS (SELECT 1 FROM information_schema.columns
                                   WHERE table_schema='public' AND table_name='employees'
                                   AND column_name='DeletedAt') THEN
                        ALTER TABLE public.employees
                            ADD COLUMN ""DeletedAt"" timestamp with time zone NULL;
                    END IF;
                END $$;");

            b.Sql(@"
                CREATE INDEX IF NOT EXISTS ""IX_employees_OrganizationId_IsDeleted""
                    ON public.employees (""OrganizationId"", ""IsDeleted"");");
        }

        protected override void Down(MigrationBuilder b)
        {
            b.Sql(@"DROP INDEX IF EXISTS public.""IX_employees_OrganizationId_IsDeleted"";");
            b.Sql(@"ALTER TABLE public.employees DROP COLUMN IF EXISTS ""IsDeleted"";");
            b.Sql(@"ALTER TABLE public.employees DROP COLUMN IF EXISTS ""DeletedAt"";");
        }
    }
}
