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

#nullable disable

namespace foodmarket.Infrastructure.Persistence.Migrations
{
    /// <summary>Phase6a — оприходование (Enter).
    ///
    /// Добавляет таблицы <c>enters</c> и <c>enter_lines</c> — документ
    /// постановки товара на склад без поставщика (начальные остатки,
    /// излишки инвентаризации). При проведении создаёт
    /// <c>stock_movements</c> с типом <c>Enter</c>.
    ///
    /// Структура зеркалит supplies/supply_lines, но без SupplierId и
    /// без логики скользящего среднего себестоимости (UnitCost — балансовая
    /// цена для отчёта, на Product.Cost не влияет).
    ///
    /// Шаги идемпотентны через IF NOT EXISTS — позволяет применять на
    /// стейджах, где таблица могла быть подсажена вручную.</summary>
    [DbContext(typeof(AppDbContext))]
    [Migration("20260528000000_Phase6a_Enters")]
    public partial class Phase6a_Enters : Migration
    {
        protected override void Up(MigrationBuilder b)
        {
            b.Sql(@"
                CREATE TABLE IF NOT EXISTS public.enters (
                    ""Id""               uuid PRIMARY KEY,
                    ""OrganizationId""   uuid NOT NULL,
                    ""Number""           varchar(50) NOT NULL,
                    ""Date""             timestamp with time zone NOT NULL,
                    ""Status""           integer NOT NULL,
                    ""StoreId""          uuid NOT NULL,
                    ""CurrencyId""       uuid NOT NULL,
                    ""Notes""            varchar(1000),
                    ""Total""            numeric(18,4) NOT NULL,
                    ""PostedAt""         timestamp with time zone,
                    ""PostedByUserId""   uuid,
                    ""CreatedAt""        timestamp with time zone NOT NULL,
                    ""UpdatedAt""        timestamp with time zone,
                    CONSTRAINT ""FK_enters_stores_StoreId"" FOREIGN KEY (""StoreId"") REFERENCES public.stores(""Id"") ON DELETE RESTRICT,
                    CONSTRAINT ""FK_enters_currencies_CurrencyId"" FOREIGN KEY (""CurrencyId"") REFERENCES public.currencies(""Id"") ON DELETE RESTRICT
                );

                CREATE UNIQUE INDEX IF NOT EXISTS ""IX_enters_OrganizationId_Number"" ON public.enters (""OrganizationId"", ""Number"");
                CREATE INDEX IF NOT EXISTS ""IX_enters_OrganizationId_Date"" ON public.enters (""OrganizationId"", ""Date"");
                CREATE INDEX IF NOT EXISTS ""IX_enters_OrganizationId_Status"" ON public.enters (""OrganizationId"", ""Status"");
                CREATE INDEX IF NOT EXISTS ""IX_enters_StoreId"" ON public.enters (""StoreId"");
                CREATE INDEX IF NOT EXISTS ""IX_enters_CurrencyId"" ON public.enters (""CurrencyId"");

                CREATE TABLE IF NOT EXISTS public.enter_lines (
                    ""Id""               uuid PRIMARY KEY,
                    ""OrganizationId""   uuid NOT NULL,
                    ""EnterId""          uuid NOT NULL,
                    ""ProductId""        uuid NOT NULL,
                    ""Quantity""         numeric(18,4) NOT NULL,
                    ""UnitCost""         numeric(18,4) NOT NULL,
                    ""LineTotal""        numeric(18,4) NOT NULL,
                    ""SortOrder""        integer NOT NULL,
                    ""CreatedAt""        timestamp with time zone NOT NULL,
                    ""UpdatedAt""        timestamp with time zone,
                    CONSTRAINT ""FK_enter_lines_enters_EnterId"" FOREIGN KEY (""EnterId"") REFERENCES public.enters(""Id"") ON DELETE CASCADE,
                    CONSTRAINT ""FK_enter_lines_products_ProductId"" FOREIGN KEY (""ProductId"") REFERENCES public.products(""Id"") ON DELETE RESTRICT
                );

                CREATE INDEX IF NOT EXISTS ""IX_enter_lines_EnterId"" ON public.enter_lines (""EnterId"");
                CREATE INDEX IF NOT EXISTS ""IX_enter_lines_ProductId"" ON public.enter_lines (""ProductId"");
                CREATE INDEX IF NOT EXISTS ""IX_enter_lines_OrganizationId_ProductId"" ON public.enter_lines (""OrganizationId"", ""ProductId"");
            ");
        }

        protected override void Down(MigrationBuilder b)
        {
            b.Sql(@"
                DROP TABLE IF EXISTS public.enter_lines;
                DROP TABLE IF EXISTS public.enters;
            ");
        }
    }
}
