import { Schema, model, Document } from "mongoose";

export interface IMessageStatsDailyUid extends Document {
  date: Date;
  dateKey: string; // YYYY-MM-DD in MessageRecordService.TIMEZONE
  strategyId?: Schema.Types.ObjectId;
  strategyName?: string;
  templateName?: string;
  cc?: string;
  image?: string;
  status: number;
  inforeground?: boolean;
  uid: string;
  msgCount: number;
  createdAt: Date;
  updatedAt: Date;
}

const messageStatsDailyUidSchema = new Schema<IMessageStatsDailyUid>(
  {
    date: { type: Date, required: true, index: true },
    dateKey: { type: String, required: true, index: true },
    strategyId: { type: Schema.Types.ObjectId, required: false },
    strategyName: { type: String, required: false, index: true },
    templateName: { type: String, required: false, index: true },
    cc: { type: String, required: false, index: true },
    image: { type: String, required: false, index: true },
    status: { type: Number, required: true, index: true },
    inforeground: { type: Boolean, required: false, index: true },
    uid: { type: String, required: true, index: true },
    msgCount: { type: Number, required: true, default: 0 },
  },
  { timestamps: true },
);

// 幂等唯一键：每天、每维度、每状态、每用户一条 rollup 记录
messageStatsDailyUidSchema.index(
  {
    dateKey: 1,
    strategyId: 1,
    strategyName: 1,
    templateName: 1,
    cc: 1,
    image: 1,
    status: 1,
    inforeground: 1,
    uid: 1,
  },
  { unique: true, name: "uniq_daily_uid_rollup" },
);

// 常见查询路径索引
messageStatsDailyUidSchema.index({ dateKey: 1, strategyName: 1 }, { name: "idx_date_strategy" });
messageStatsDailyUidSchema.index({ dateKey: 1, templateName: 1 }, { name: "idx_date_template" });
messageStatsDailyUidSchema.index({ dateKey: 1, cc: 1 }, { name: "idx_date_cc" });
messageStatsDailyUidSchema.index({ dateKey: 1, image: 1 }, { name: "idx_date_image" });

export const MessageStatsDailyUid = model<IMessageStatsDailyUid>("MessageStatsDailyUid", messageStatsDailyUidSchema);
