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

#nullable disable

namespace foodmarket.Infrastructure.Persistence.Migrations
{
    /// <summary>Phase8b — org_audit_log: per-tenant журнал мутаций.
    ///
    /// Пишется через OrgAuditInterceptor (SaveChangesInterceptor) на
    /// отслеживаемые типы. Tenant-scoped — query-filter ограничивает выборку
    /// своей оргой; SuperAdmin без override видит всё. ChangesJson — jsonb
    /// формата { "field": { "before": ..., "after": ... } }.</summary>
    [DbContext(typeof(AppDbContext))]
    [Migration("20260528210000_Phase8b_OrgAuditLog")]
    public partial class Phase8b_OrgAuditLog : Migration
    {
        protected override void Up(MigrationBuilder b)
        {
            b.Sql(@"
                CREATE TABLE IF NOT EXISTS public.org_audit_log (
                    ""Id""             uuid PRIMARY KEY,
                    ""OrganizationId"" uuid NOT NULL,
                    ""UserId""         uuid,
                    ""Action""         varchar(20) NOT NULL,
                    ""EntityType""     varchar(100) NOT NULL,
                    ""EntityId""       uuid,
                    ""ChangesJson""    jsonb NOT NULL,
                    ""CreatedAt""      timestamp with time zone NOT NULL,
                    ""UpdatedAt""      timestamp with time zone
                );

                CREATE INDEX IF NOT EXISTS ""IX_org_audit_log_OrganizationId_CreatedAt""
                    ON public.org_audit_log (""OrganizationId"", ""CreatedAt"");
                CREATE INDEX IF NOT EXISTS ""IX_org_audit_log_OrganizationId_EntityType_EntityId""
                    ON public.org_audit_log (""OrganizationId"", ""EntityType"", ""EntityId"");
                CREATE INDEX IF NOT EXISTS ""IX_org_audit_log_OrganizationId_UserId_CreatedAt""
                    ON public.org_audit_log (""OrganizationId"", ""UserId"", ""CreatedAt"");
            ");
        }

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