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

#nullable disable

namespace foodmarket.Infrastructure.Persistence.Migrations
{
    /// <summary>Phase6e — расширение RetailSale возвратами от покупателя.
    ///
    /// Добавляет колонки:
    /// • retail_sales.IsReturn (bool) — флаг документа возврата;
    /// • retail_sales.ReferenceSaleId (uuid?) — ссылка на исходный чек;
    /// • retail_sale_lines.QtyReturned (numeric 18,4) — сколько уже возвращено
    ///   из исходной строки (агрегация для защиты от over-return).
    ///
    /// Идемпотентно: все шаги через IF NOT EXISTS.</summary>
    [DbContext(typeof(AppDbContext))]
    [Migration("20260528040000_Phase6e_RetailSaleReturns")]
    public partial class Phase6e_RetailSaleReturns : Migration
    {
        protected override void Up(MigrationBuilder b)
        {
            b.Sql(@"
                DO $$
                BEGIN
                    IF NOT EXISTS (SELECT 1 FROM information_schema.columns
                                   WHERE table_schema='public' AND table_name='retail_sales'
                                   AND column_name='IsReturn') THEN
                        ALTER TABLE public.retail_sales ADD COLUMN ""IsReturn"" boolean NOT NULL DEFAULT false;
                    END IF;

                    IF NOT EXISTS (SELECT 1 FROM information_schema.columns
                                   WHERE table_schema='public' AND table_name='retail_sales'
                                   AND column_name='ReferenceSaleId') THEN
                        ALTER TABLE public.retail_sales ADD COLUMN ""ReferenceSaleId"" uuid;
                        ALTER TABLE public.retail_sales
                            ADD CONSTRAINT ""FK_retail_sales_retail_sales_ReferenceSaleId""
                            FOREIGN KEY (""ReferenceSaleId"") REFERENCES public.retail_sales(""Id"") ON DELETE RESTRICT;
                    END IF;

                    IF NOT EXISTS (SELECT 1 FROM information_schema.columns
                                   WHERE table_schema='public' AND table_name='retail_sale_lines'
                                   AND column_name='QtyReturned') THEN
                        ALTER TABLE public.retail_sale_lines ADD COLUMN ""QtyReturned"" numeric(18,4) NOT NULL DEFAULT 0;
                    END IF;
                END $$;

                CREATE INDEX IF NOT EXISTS ""IX_retail_sales_OrganizationId_IsReturn""
                    ON public.retail_sales (""OrganizationId"", ""IsReturn"");
                CREATE INDEX IF NOT EXISTS ""IX_retail_sales_ReferenceSaleId""
                    ON public.retail_sales (""ReferenceSaleId"");
            ");
        }

        protected override void Down(MigrationBuilder b)
        {
            b.Sql(@"
                ALTER TABLE public.retail_sale_lines DROP COLUMN IF EXISTS ""QtyReturned"";
                ALTER TABLE public.retail_sales DROP CONSTRAINT IF EXISTS ""FK_retail_sales_retail_sales_ReferenceSaleId"";
                DROP INDEX IF EXISTS public.""IX_retail_sales_OrganizationId_IsReturn"";
                DROP INDEX IF EXISTS public.""IX_retail_sales_ReferenceSaleId"";
                ALTER TABLE public.retail_sales DROP COLUMN IF EXISTS ""ReferenceSaleId"";
                ALTER TABLE public.retail_sales DROP COLUMN IF EXISTS ""IsReturn"";
            ");
        }
    }
}
