using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace foodmarket.Infrastructure.Persistence.Migrations
{
    /// <summary>products.ProductGroupId становится NOT NULL.
    /// Backfill: для каждой организации с товарами без группы создаётся
    /// (если ещё нет) группа «Продукты питания», все NULL-товары
    /// привязываются к ней; затем колонка ставится NOT NULL.</summary>
    public partial class Phase5g_RequiredProductGroup : Migration
    {
        protected override void Up(MigrationBuilder b)
        {
            b.Sql("""
                INSERT INTO public.product_groups
                    ("Id", "OrganizationId", "Name", "Path", "SortOrder", "IsActive", "CreatedAt")
                SELECT gen_random_uuid(), o."OrganizationId", 'Продукты питания',
                       'Продукты питания', 0, true, now() AT TIME ZONE 'UTC'
                FROM (
                    SELECT DISTINCT "OrganizationId" FROM public.products WHERE "ProductGroupId" IS NULL
                ) o
                WHERE NOT EXISTS (
                    SELECT 1 FROM public.product_groups pg
                    WHERE pg."OrganizationId" = o."OrganizationId" AND pg."Name" = 'Продукты питания'
                );
            """);

            b.Sql("""
                UPDATE public.products p
                SET "ProductGroupId" = pg."Id"
                FROM public.product_groups pg
                WHERE pg."OrganizationId" = p."OrganizationId"
                  AND pg."Name" = 'Продукты питания'
                  AND p."ProductGroupId" IS NULL;
            """);

            b.AlterColumn<System.Guid>(
                name: "ProductGroupId", schema: "public", table: "products",
                type: "uuid", nullable: false,
                oldClrType: typeof(System.Guid), oldType: "uuid", oldNullable: true);
        }

        protected override void Down(MigrationBuilder b)
        {
            b.AlterColumn<System.Guid>(
                name: "ProductGroupId", schema: "public", table: "products",
                type: "uuid", nullable: true,
                oldClrType: typeof(System.Guid), oldType: "uuid", oldNullable: false);
        }
    }
}
