using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using line_gestao_api.Data; #nullable disable namespace line_gestao_api.Migrations { [DbContext(typeof(AppDbContext))] [Migration("20260226130200_BackfillTenantsFromDistinctMobileLinesCliente")] public partial class BackfillTenantsFromDistinctMobileLinesCliente : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql(""" DO $$ BEGIN IF EXISTS ( SELECT 1 FROM "MobileLines" WHERE "Cliente" IS NULL OR btrim("Cliente") = '' ) THEN RAISE EXCEPTION 'Backfill abortado: MobileLines.Cliente possui valores NULL/vazios. Corrija os dados antes de migrar.'; END IF; END $$; """); migrationBuilder.Sql("""CREATE EXTENSION IF NOT EXISTS pgcrypto;"""); migrationBuilder.Sql(""" INSERT INTO "Tenants" ( "Id", "NomeOficial", "IsSystem", "Ativo", "SourceType", "SourceKey", "CreatedAt" ) SELECT gen_random_uuid(), src."Cliente", FALSE, TRUE, 'MobileLines.Cliente', src."Cliente", NOW() FROM ( SELECT DISTINCT "Cliente" FROM "MobileLines" ) src LEFT JOIN "Tenants" t ON t."SourceType" = 'MobileLines.Cliente' AND t."SourceKey" = src."Cliente" WHERE t."Id" IS NULL; """); migrationBuilder.Sql(""" UPDATE "Tenants" SET "NomeOficial" = "SourceKey", "IsSystem" = FALSE, "Ativo" = TRUE WHERE "SourceType" = 'MobileLines.Cliente' AND "SourceKey" IS NOT NULL; """); } protected override void Down(MigrationBuilder migrationBuilder) { // No-op intencional. Evita remover tenants já em uso. } } }