import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

// C2C 订单类型常量
const C2C_ORDER_TYPE = {
  BUY: 'BUY',
  SELL: 'SELL',
} as const;

// C2C 订单状态常量
const C2C_ORDER_STATUS = {
  PENDING: 'PENDING',
  MATCHED: 'MATCHED',
  PAID: 'PAID',
  COMPLETED: 'COMPLETED',
  CANCELLED: 'CANCELLED',
  EXPIRED: 'EXPIRED',
} as const;

type C2cOrderType = typeof C2C_ORDER_TYPE[keyof typeof C2C_ORDER_TYPE];
type C2cOrderStatus = typeof C2C_ORDER_STATUS[keyof typeof C2C_ORDER_STATUS];

export interface C2cOrderEntity {
  id: string;
  orderNo: string;
  type: C2cOrderType;
  status: C2cOrderStatus;
  makerAccountSequence: string;
  makerUserId?: string | null;
  makerPhone?: string | null;
  makerNickname?: string | null;
  takerAccountSequence?: string | null;
  takerUserId?: string | null;
  takerPhone?: string | null;
  takerNickname?: string | null;
  price: string;
  quantity: string;
  totalAmount: string;
  minAmount: string;
  maxAmount: string;
  // 收款信息
  paymentMethod?: string | null;
  paymentAccount?: string | null;
  paymentQrCode?: string | null;
  paymentRealName?: string | null;
  // 超时配置
  paymentTimeoutMinutes: number;
  confirmTimeoutMinutes: number;
  paymentDeadline?: Date | null;
  confirmDeadline?: Date | null;
  // 付款水单
  paymentProofUrl?: string | null;
  // Bot 自动购买相关
  sellerKavaAddress?: string | null;
  botPurchased: boolean;
  paymentTxHash?: string | null;
  // 其他
  remark?: string | null;
  createdAt: Date;
  updatedAt: Date;
  matchedAt?: Date | null;
  paidAt?: Date | null;
  completedAt?: Date | null;
  cancelledAt?: Date | null;
  expiredAt?: Date | null;
}

@Injectable()
export class C2cOrderRepository {
  constructor(private readonly prisma: PrismaService) {}

  /**
   * 根据ID查询订单
   */
  async findById(id: string): Promise<C2cOrderEntity | null> {
    const record = await this.prisma.c2cOrder.findUnique({ where: { id } });
    return record ? this.toEntity(record) : null;
  }

  /**
   * 根据订单号查询订单
   */
  async findByOrderNo(orderNo: string): Promise<C2cOrderEntity | null> {
    const record = await this.prisma.c2cOrder.findUnique({ where: { orderNo } });
    return record ? this.toEntity(record) : null;
  }

  /**
   * 创建订单
   */
  async create(data: {
    orderNo: string;
    type: C2cOrderType;
    makerAccountSequence: string;
    makerUserId?: string;
    makerPhone?: string;
    makerNickname?: string;
    price: string;
    quantity: string;
    totalAmount: string;
    minAmount?: string;
    maxAmount?: string;
    // 收款信息
    paymentMethod?: string;
    paymentAccount?: string;
    paymentQrCode?: string;
    paymentRealName?: string;
    // 卖家 Kava 地址
    sellerKavaAddress?: string | null;
    remark?: string;
  }): Promise<C2cOrderEntity> {
    const record = await this.prisma.c2cOrder.create({
      data: {
        orderNo: data.orderNo,
        type: data.type as any,
        status: C2C_ORDER_STATUS.PENDING as any,
        makerAccountSequence: data.makerAccountSequence,
        makerUserId: data.makerUserId,
        makerPhone: data.makerPhone,
        makerNickname: data.makerNickname,
        price: data.price,
        quantity: data.quantity,
        totalAmount: data.totalAmount,
        minAmount: data.minAmount || '0',
        maxAmount: data.maxAmount || '0',
        // 收款信息
        paymentMethod: data.paymentMethod,
        paymentAccount: data.paymentAccount,
        paymentQrCode: data.paymentQrCode,
        paymentRealName: data.paymentRealName,
        // 卖家 Kava 地址
        sellerKavaAddress: data.sellerKavaAddress,
        remark: data.remark,
      },
    });
    return this.toEntity(record);
  }

  /**
   * 更新订单状态
   */
  async updateStatus(
    orderNo: string,
    status: C2cOrderStatus,
    additionalData?: Partial<{
      takerAccountSequence: string;
      takerUserId: string;
      takerPhone: string;
      takerNickname: string;
      // 收款信息（接买单时由taker提供）
      paymentMethod: string;
      paymentAccount: string;
      paymentQrCode: string;
      paymentRealName: string;
      // #13: 部分成交时更新数量和金额
      quantity: string;
      totalAmount: string;
      // 付款水单
      paymentProofUrl: string;
      // 超时时间
      paymentDeadline: Date;
      confirmDeadline: Date;
      // 时间戳
      matchedAt: Date;
      paidAt: Date;
      completedAt: Date;
      cancelledAt: Date;
      expiredAt: Date;
    }>,
  ): Promise<C2cOrderEntity | null> {
    const record = await this.prisma.c2cOrder.update({
      where: { orderNo },
      data: {
        status: status as any,
        ...additionalData,
      },
    });
    return this.toEntity(record);
  }

  /**
   * 查询超时订单（用于定时任务）
   * @param pendingCutoff 可选，PENDING 订单的过期截止时间（早于此时间的 PENDING 订单视为超时）
   */
  async findExpiredOrders(pendingCutoff?: Date): Promise<C2cOrderEntity[]> {
    const now = new Date();
    const orConditions: any[] = [
      // MATCHED状态但付款超时
      {
        status: C2C_ORDER_STATUS.MATCHED as any,
        paymentDeadline: { lt: now },
      },
      // PAID状态但确认超时
      {
        status: C2C_ORDER_STATUS.PAID as any,
        confirmDeadline: { lt: now },
      },
    ];

    // PENDING状态超时（挂单超时未被接单，自动取消）
    if (pendingCutoff) {
      orConditions.push({
        status: C2C_ORDER_STATUS.PENDING as any,
        createdAt: { lt: pendingCutoff },
      });
    }

    const records = await this.prisma.c2cOrder.findMany({
      where: { OR: orConditions },
    });
    return records.map((r: any) => this.toEntity(r));
  }

  /**
   * 查询市场订单列表（待接单的广告）
   */
  async findMarketOrders(options: {
    type?: C2cOrderType;
    page: number;
    pageSize: number;
    excludeAccountSequence?: string;
  }): Promise<{ data: C2cOrderEntity[]; total: number }> {
    const where: any = {
      status: C2C_ORDER_STATUS.PENDING,
    };
    if (options.type) {
      where.type = options.type;
    }
    // 排除自己的订单
    if (options.excludeAccountSequence) {
      where.makerAccountSequence = { not: options.excludeAccountSequence };
    }

    const [records, total] = await Promise.all([
      this.prisma.c2cOrder.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (options.page - 1) * options.pageSize,
        take: options.pageSize,
      }),
      this.prisma.c2cOrder.count({ where }),
    ]);

    return {
      data: records.map((r: any) => this.toEntity(r)),
      total,
    };
  }

  /**
   * 查询用户自己的订单（包含作为maker和taker的订单）
   */
  async findByAccountSequence(
    accountSequence: string,
    options: {
      status?: C2cOrderStatus;
      page: number;
      pageSize: number;
    },
  ): Promise<{ data: C2cOrderEntity[]; total: number }> {
    const where: any = {
      OR: [{ makerAccountSequence: accountSequence }, { takerAccountSequence: accountSequence }],
    };
    if (options.status) {
      where.status = options.status;
    }

    const [records, total] = await Promise.all([
      this.prisma.c2cOrder.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (options.page - 1) * options.pageSize,
        take: options.pageSize,
      }),
      this.prisma.c2cOrder.count({ where }),
    ]);

    return {
      data: records.map((r: any) => this.toEntity(r)),
      total,
    };
  }

  /**
   * 查询用户挂出的待接单订单
   */
  async findPendingByMaker(makerAccountSequence: string): Promise<C2cOrderEntity[]> {
    const records = await this.prisma.c2cOrder.findMany({
      where: {
        makerAccountSequence,
        status: C2C_ORDER_STATUS.PENDING as any,
      },
      orderBy: { createdAt: 'desc' },
    });
    return records.map((r: any) => this.toEntity(r));
  }

  /**
   * 查询待处理的卖单（供 Bot 自动购买）
   * 只返回未被 Bot 购买的 PENDING 状态卖单
   */
  async findPendingSellOrdersForBot(limit: number): Promise<C2cOrderEntity[]> {
    const records = await this.prisma.c2cOrder.findMany({
      where: {
        type: C2C_ORDER_TYPE.SELL as any,
        status: C2C_ORDER_STATUS.PENDING as any,
        botPurchased: false,
      },
      orderBy: { createdAt: 'asc' }, // 先进先出
      take: limit,
    });
    return records.map((r: any) => this.toEntity(r));
  }

  /**
   * 更新订单为 Bot 已购买状态
   */
  async updateBotPurchase(
    orderNo: string,
    data: {
      sellerKavaAddress: string;
      paymentTxHash: string;
    },
  ): Promise<C2cOrderEntity | null> {
    const record = await this.prisma.c2cOrder.update({
      where: { orderNo },
      data: {
        botPurchased: true,
        sellerKavaAddress: data.sellerKavaAddress,
        paymentTxHash: data.paymentTxHash,
        status: C2C_ORDER_STATUS.COMPLETED as any,
        completedAt: new Date(),
        paidAt: new Date(),
      },
    });
    return this.toEntity(record);
  }

  /**
   * 更新付款水单URL
   */
  async updatePaymentProof(orderNo: string, paymentProofUrl: string): Promise<C2cOrderEntity | null> {
    const record = await this.prisma.c2cOrder.update({
      where: { orderNo },
      data: { paymentProofUrl },
    });
    return this.toEntity(record);
  }

  /**
   * 查询 Bot 购买的订单（分页）
   */
  async findBotPurchasedOrders(options: {
    page: number;
    pageSize: number;
  }): Promise<{ data: C2cOrderEntity[]; total: number }> {
    const where = { botPurchased: true };
    const [records, total] = await Promise.all([
      this.prisma.c2cOrder.findMany({
        where,
        orderBy: { completedAt: 'desc' },
        skip: (options.page - 1) * options.pageSize,
        take: options.pageSize,
      }),
      this.prisma.c2cOrder.count({ where }),
    ]);
    return {
      data: records.map((r: any) => this.toEntity(r)),
      total,
    };
  }

  /**
   * 获取 Bot 统计数据（总订单数、总金额）
   */
  async getBotStats(): Promise<{ totalOrders: number; totalAmount: string }> {
    const [count, sum] = await Promise.all([
      this.prisma.c2cOrder.count({ where: { botPurchased: true } }),
      this.prisma.c2cOrder.aggregate({
        where: { botPurchased: true },
        _sum: { totalAmount: true },
      }),
    ]);
    return {
      totalOrders: count,
      totalAmount: sum._sum.totalAmount?.toString() || '0',
    };
  }

  /**
   * 将Prisma记录转为实体
   */
  private toEntity(record: any): C2cOrderEntity {
    return {
      id: record.id,
      orderNo: record.orderNo,
      type: record.type as C2cOrderType,
      status: record.status as C2cOrderStatus,
      makerAccountSequence: record.makerAccountSequence,
      makerUserId: record.makerUserId,
      makerPhone: record.makerPhone,
      makerNickname: record.makerNickname,
      takerAccountSequence: record.takerAccountSequence,
      takerUserId: record.takerUserId,
      takerPhone: record.takerPhone,
      takerNickname: record.takerNickname,
      price: record.price.toString(),
      quantity: record.quantity.toString(),
      totalAmount: record.totalAmount.toString(),
      minAmount: record.minAmount.toString(),
      maxAmount: record.maxAmount.toString(),
      // 收款信息
      paymentMethod: record.paymentMethod,
      paymentAccount: record.paymentAccount,
      paymentQrCode: record.paymentQrCode,
      paymentRealName: record.paymentRealName,
      // 超时配置
      paymentTimeoutMinutes: record.paymentTimeoutMinutes,
      confirmTimeoutMinutes: record.confirmTimeoutMinutes,
      paymentDeadline: record.paymentDeadline,
      confirmDeadline: record.confirmDeadline,
      // 付款水单
      paymentProofUrl: record.paymentProofUrl,
      // Bot 自动购买相关
      sellerKavaAddress: record.sellerKavaAddress,
      botPurchased: record.botPurchased,
      paymentTxHash: record.paymentTxHash,
      // 其他
      remark: record.remark,
      createdAt: record.createdAt,
      updatedAt: record.updatedAt,
      matchedAt: record.matchedAt,
      paidAt: record.paidAt,
      completedAt: record.completedAt,
      cancelledAt: record.cancelledAt,
      expiredAt: record.expiredAt,
    };
  }
}
