using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace foodmarket.Infrastructure.Persistence.Migrations
{
    /// <summary>Phase3b — рационализация модели:
    /// - DROP IsActive у products / product_groups / units_of_measure / counterparties / price_types.
    /// - DROP organizations.MultiplePriceTypesEnabled (раздел «Типы цен» теперь всегда виден).
    /// - DROP price_types.IsActive (системная запись неудаляема, остальные удаляются физически).
    /// - ADD price_types.IsRequired bool default false.
    /// - ADD price_types.IsSystem bool default false.
    /// - ADD products.ShelfLifeDays integer NULL.
    /// - Гарантирует существование одной системной записи «Розничная цена»
    ///   (IsSystem=true, IsRequired=true) в каждой организации.</summary>
    public partial class Phase3b_PricingCleanup : Migration
    {
        protected override void Up(MigrationBuilder b)
        {
            // На products был индекс (OrganizationId, IsActive) — удалим до dropколонки.
            b.Sql("DROP INDEX IF EXISTS public.\"IX_products_OrganizationId_IsActive\";");

            b.DropColumn(name: "IsActive", schema: "public", table: "products");
            b.DropColumn(name: "IsActive", schema: "public", table: "product_groups");
            b.DropColumn(name: "IsActive", schema: "public", table: "units_of_measure");
            b.DropColumn(name: "IsActive", schema: "public", table: "counterparties");
            b.DropColumn(name: "IsActive", schema: "public", table: "price_types");
            b.DropColumn(name: "MultiplePriceTypesEnabled", schema: "public", table: "organizations");

            b.AddColumn<bool>(
                name: "IsRequired", schema: "public", table: "price_types",
                type: "boolean", nullable: false, defaultValue: false);
            b.AddColumn<bool>(
                name: "IsSystem", schema: "public", table: "price_types",
                type: "boolean", nullable: false, defaultValue: false);

            b.AddColumn<int>(
                name: "ShelfLifeDays", schema: "public", table: "products",
                type: "integer", nullable: true);

            // Гарантируем системную «Розничная цена» в каждой организации.
            b.Sql("""
                INSERT INTO public.price_types
                    ("Id", "OrganizationId", "Name", "IsRequired", "IsSystem", "IsDefault", "IsRetail", "SortOrder", "CreatedAt")
                SELECT gen_random_uuid(), o."Id", 'Розничная цена', true, true, true, true, 0, now() AT TIME ZONE 'UTC'
                FROM public.organizations o
                WHERE NOT EXISTS (
                    SELECT 1 FROM public.price_types pt
                    WHERE pt."OrganizationId" = o."Id" AND pt."IsSystem" = true
                );
            """);

            // Если в организации есть «Розничная цена», но она не помечена системной — пометим её.
            b.Sql("""
                UPDATE public.price_types
                SET "IsSystem" = true, "IsRequired" = true
                WHERE "Name" = 'Розничная цена'
                  AND "IsSystem" = false
                  AND "OrganizationId" IN (
                      SELECT "OrganizationId" FROM public.price_types
                      GROUP BY "OrganizationId"
                      HAVING SUM(CASE WHEN "IsSystem" THEN 1 ELSE 0 END) = 0
                  );
            """);
        }

        protected override void Down(MigrationBuilder b)
        {
            b.DropColumn(name: "ShelfLifeDays", schema: "public", table: "products");
            b.DropColumn(name: "IsSystem", schema: "public", table: "price_types");
            b.DropColumn(name: "IsRequired", schema: "public", table: "price_types");

            b.AddColumn<bool>(name: "MultiplePriceTypesEnabled", schema: "public", table: "organizations",
                type: "boolean", nullable: false, defaultValue: false);
            b.AddColumn<bool>(name: "IsActive", schema: "public", table: "price_types",
                type: "boolean", nullable: false, defaultValue: true);
            b.AddColumn<bool>(name: "IsActive", schema: "public", table: "counterparties",
                type: "boolean", nullable: false, defaultValue: true);
            b.AddColumn<bool>(name: "IsActive", schema: "public", table: "units_of_measure",
                type: "boolean", nullable: false, defaultValue: true);
            b.AddColumn<bool>(name: "IsActive", schema: "public", table: "product_groups",
                type: "boolean", nullable: false, defaultValue: true);
            b.AddColumn<bool>(name: "IsActive", schema: "public", table: "products",
                type: "boolean", nullable: false, defaultValue: true);
        }
    }
}
