const { CopyTrader } = require("../../models");
const { ValidationError, NotFoundError } = require("../../utils/errors");

class adminCopyTradersService {
  async getCopyTraders() {
    const rows = await CopyTrader.findAll({ order: [["created_at", "DESC"]] });
    return {
      traders: rows.map(t => ({
        id: t.id,
        name: t.name,
        status: t.status,
        verified: !!t.verified,
        feeRate: Number(t.feeRate ?? 0),
        winRate: Number(t.winRate ?? 0),
        pnl30d: Number(t.pnl30d ?? 0),
        aum: Number(t.aum ?? 0),
        followers: Number(t.followers ?? 0),
      })),
    };
  }

  async createCopyTrader(data) {
    const { name } = data;
    if (!name) throw new ValidationError("name is required");
    const trader = await CopyTrader.create({ name, status: "active", verified: false });
    return trader;
  }

  async updateCopyTrader(copyTraderId, data) {
    const trader = await CopyTrader.findByPk(copyTraderId);
    if (!trader) throw new NotFoundError("Copy trader not found");
    await trader.update(data);
    return trader;
  }

  async pauseCopyTrader(copyTraderId) {
    const trader = await CopyTrader.findByPk(copyTraderId);
    if (!trader) throw new NotFoundError("Copy trader not found");
    await trader.update({ status: "paused" });
    return trader;
  }

  async resumeCopyTrader(copyTraderId) {
    const trader = await CopyTrader.findByPk(copyTraderId);
    if (!trader) throw new NotFoundError("Copy trader not found");
    await trader.update({ status: "active" });
    return trader;
  }
}

module.exports = new adminCopyTradersService();
