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

#nullable disable

namespace foodmarket.Infrastructure.Persistence.Migrations
{
    /// <summary>Phase8c — таблица import_jobs для persisted прогресса фоновых
    /// импортов из MoySklad. Раньше состояние жило в ConcurrentDictionary
    /// внутри Singleton-сервиса, рестарт процесса терял всё (TD-5).
    /// Теперь Create() пишет строку немедленно, SaveAsync() обновляет,
    /// AdminJobsController читает из БД.</summary>
    [DbContext(typeof(AppDbContext))]
    [Migration("20260528220000_Phase8c_ImportJobs")]
    public partial class Phase8c_ImportJobs : Migration
    {
        protected override void Up(MigrationBuilder b)
        {
            b.Sql(@"
                CREATE TABLE IF NOT EXISTS public.import_jobs (
                    ""Id""             uuid PRIMARY KEY,
                    ""OrganizationId"" uuid NOT NULL,
                    ""Kind""           varchar(50) NOT NULL,
                    ""StartedAt""      timestamp with time zone NOT NULL,
                    ""FinishedAt""     timestamp with time zone,
                    ""Status""         integer NOT NULL,
                    ""Stage""          varchar(500),
                    ""Total""          integer NOT NULL DEFAULT 0,
                    ""Created""        integer NOT NULL DEFAULT 0,
                    ""Updated""        integer NOT NULL DEFAULT 0,
                    ""Skipped""        integer NOT NULL DEFAULT 0,
                    ""Deleted""        integer NOT NULL DEFAULT 0,
                    ""GroupsCreated""  integer NOT NULL DEFAULT 0,
                    ""Message""        varchar(2000),
                    ""ErrorsJson""     jsonb NOT NULL DEFAULT '[]'::jsonb,
                    ""CreatedAt""      timestamp with time zone NOT NULL,
                    ""UpdatedAt""      timestamp with time zone
                );

                CREATE INDEX IF NOT EXISTS ""IX_import_jobs_OrganizationId_StartedAt""
                    ON public.import_jobs (""OrganizationId"", ""StartedAt"");
                CREATE INDEX IF NOT EXISTS ""IX_import_jobs_OrganizationId_Status""
                    ON public.import_jobs (""OrganizationId"", ""Status"");
                CREATE INDEX IF NOT EXISTS ""IX_import_jobs_FinishedAt""
                    ON public.import_jobs (""FinishedAt"");
            ");
        }

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