using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using TakeoutSaaS.Infrastructure.App.Persistence;

#nullable disable

namespace TakeoutSaaS.Infrastructure.Migrations;

/// <summary>
/// 新增经营报表快照与成本配置表结构。
/// </summary>
[DbContext(typeof(TakeoutAppDbContext))]
[Migration("20260305090000_AddFinanceBusinessReportModule")]
public sealed class AddFinanceBusinessReportModule : Migration
{
    /// <inheritdoc />
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "finance_business_report_snapshots",
            columns: table => new
            {
                Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
                    .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
                StoreId = table.Column<long>(type: "bigint", nullable: false, comment: "所属门店 ID。"),
                PeriodType = table.Column<int>(type: "integer", nullable: false, comment: "周期类型。"),
                PeriodStartAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "周期开始时间（UTC，含）。"),
                PeriodEndAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "周期结束时间（UTC，不含）。"),
                Status = table.Column<int>(type: "integer", nullable: false, comment: "生成状态。"),
                RevenueAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "营业额。"),
                OrderCount = table.Column<int>(type: "integer", nullable: false, comment: "订单数。"),
                AverageOrderValue = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "客单价。"),
                RefundRate = table.Column<decimal>(type: "numeric(9,4)", precision: 9, scale: 4, nullable: false, comment: "退款率（0-1）。"),
                CostTotalAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "成本总额。"),
                NetProfitAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "净利润。"),
                ProfitRate = table.Column<decimal>(type: "numeric(9,4)", precision: 9, scale: 4, nullable: false, comment: "利润率（0-1）。"),
                KpiComparisonJson = table.Column<string>(type: "text", nullable: false, comment: "KPI 比较快照 JSON（同比/环比）。"),
                IncomeBreakdownJson = table.Column<string>(type: "text", nullable: false, comment: "收入明细快照 JSON（按渠道）。"),
                CostBreakdownJson = table.Column<string>(type: "text", nullable: false, comment: "成本明细快照 JSON（按类别）。"),
                StartedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "生成开始时间（UTC）。"),
                FinishedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "生成完成时间（UTC）。"),
                LastError = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: true, comment: "最近一次失败信息。"),
                RetryCount = table.Column<int>(type: "integer", nullable: false, defaultValue: 0, comment: "重试次数。"),
                HangfireJobId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true, comment: "调度任务 ID。"),
                CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间（UTC）。"),
                UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间（UTC），从未更新时为 null。"),
                DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间（UTC），未删除时为 null。"),
                CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识，匿名或系统操作时为 null。"),
                UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识，匿名或系统操作时为 null。"),
                DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识（软删除），未删除时为 null。"),
                TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_finance_business_report_snapshots", x => x.Id);
            },
            comment: "经营报表快照实体。");

        migrationBuilder.CreateTable(
            name: "finance_cost_profiles",
            columns: table => new
            {
                Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
                    .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
                StoreId = table.Column<long>(type: "bigint", nullable: false, comment: "门店 ID。"),
                Category = table.Column<int>(type: "integer", nullable: false, comment: "成本分类。"),
                CalcMode = table.Column<int>(type: "integer", nullable: false, comment: "计算模式。"),
                Ratio = table.Column<decimal>(type: "numeric(9,6)", precision: 9, scale: 6, nullable: false, comment: "比例值（0-1）。"),
                FixedDailyAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "固定日金额。"),
                EffectiveFrom = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "生效开始日期（UTC 日期）。"),
                EffectiveTo = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "生效结束日期（UTC 日期，含）。"),
                IsEnabled = table.Column<bool>(type: "boolean", nullable: false, comment: "是否启用。"),
                SortOrder = table.Column<int>(type: "integer", nullable: false, defaultValue: 100, comment: "排序值。"),
                CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间（UTC）。"),
                UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间（UTC），从未更新时为 null。"),
                DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间（UTC），未删除时为 null。"),
                CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识，匿名或系统操作时为 null。"),
                UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识，匿名或系统操作时为 null。"),
                DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识（软删除），未删除时为 null。"),
                TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_finance_cost_profiles", x => x.Id);
            },
            comment: "成本配置实体（类别级规则）。");

        migrationBuilder.CreateTable(
            name: "finance_cost_daily_overrides",
            columns: table => new
            {
                Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
                    .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
                StoreId = table.Column<long>(type: "bigint", nullable: false, comment: "门店 ID。"),
                BusinessDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "业务日期（UTC 日期）。"),
                Category = table.Column<int>(type: "integer", nullable: false, comment: "成本分类。"),
                Amount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "覆盖金额。"),
                Remark = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true, comment: "备注。"),
                CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间（UTC）。"),
                UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间（UTC），从未更新时为 null。"),
                DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间（UTC），未删除时为 null。"),
                CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识，匿名或系统操作时为 null。"),
                UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识，匿名或系统操作时为 null。"),
                DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识（软删除），未删除时为 null。"),
                TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_finance_cost_daily_overrides", x => x.Id);
            },
            comment: "成本日覆盖实体。");

        migrationBuilder.CreateIndex(
            name: "IX_finance_business_report_snapshots_TenantId_Status_CreatedAt",
            table: "finance_business_report_snapshots",
            columns: new[] { "TenantId", "Status", "CreatedAt" });

        migrationBuilder.CreateIndex(
            name: "IX_finance_business_report_snapshots_TenantId_StoreId_PeriodType_S~",
            table: "finance_business_report_snapshots",
            columns: new[] { "TenantId", "StoreId", "PeriodType", "Status", "PeriodStartAt" });

        migrationBuilder.CreateIndex(
            name: "IX_finance_business_report_snapshots_TenantId_StoreId_PeriodType_P~",
            table: "finance_business_report_snapshots",
            columns: new[] { "TenantId", "StoreId", "PeriodType", "PeriodStartAt" },
            unique: true);

        migrationBuilder.CreateIndex(
            name: "IX_finance_cost_daily_overrides_TenantId_StoreId_BusinessDate",
            table: "finance_cost_daily_overrides",
            columns: new[] { "TenantId", "StoreId", "BusinessDate" });

        migrationBuilder.CreateIndex(
            name: "IX_finance_cost_daily_overrides_TenantId_StoreId_BusinessDate_Cate~",
            table: "finance_cost_daily_overrides",
            columns: new[] { "TenantId", "StoreId", "BusinessDate", "Category" },
            unique: true);

        migrationBuilder.CreateIndex(
            name: "IX_finance_cost_profiles_TenantId_StoreId_Category_EffectiveFrom_E~",
            table: "finance_cost_profiles",
            columns: new[] { "TenantId", "StoreId", "Category", "EffectiveFrom", "EffectiveTo" });

        migrationBuilder.CreateIndex(
            name: "IX_finance_cost_profiles_TenantId_StoreId_IsEnabled_SortOrder",
            table: "finance_cost_profiles",
            columns: new[] { "TenantId", "StoreId", "IsEnabled", "SortOrder" });
    }

    /// <inheritdoc />
    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "finance_business_report_snapshots");

        migrationBuilder.DropTable(
            name: "finance_cost_daily_overrides");

        migrationBuilder.DropTable(
            name: "finance_cost_profiles");
    }
}
