import { prisma } from "../prisma/db";
import { xcxApi } from "../utils/server";
import { KaiqiuService } from "./KaiqiuService";

export class EventSubscribeService {
  public static async sub(user: string, event: string) {
    const success = await prisma.eventSubs.create({ data: { logto_uid: user, event_id: event }})
    .then(() => true)
    .catch(e => {
      console.debug('Subscribe user: %s, event: %s, error: %s', user, event, e);
      return false;
    });
    return success;
  }
  public static async unSub(user: string, event: string) {
    const success = await prisma.eventSubs.deleteMany({
      where: { logto_uid: user, event_id: event },
    })
    .then(() => true)
    .catch(() => false);
    return success;
  }
  public static isSub(user: string, event: string) {
    return prisma.eventSubs.count({
      where: { logto_uid: user, event_id: event },
    }).then(value => value > 0);
  }
  public static async getUsers(event: string) {
    const users = await prisma.eventSubs
      .findMany({
        where: { event_id: event },
        select: { logto_uid: true },
        distinct: 'logto_uid',
      })
      .then(value => value.map(e => e.logto_uid))
    return users;
  }
  public static async getEvents(user?: string) {
    const events = await prisma.eventSubs.findMany({
      where: user ? { logto_uid: user } : {},
      select: { event_id: true },
      distinct: 'event_id',
    }).then(value => value.map(e => e.event_id));
    return events;
  }
  public static async getAllEvents() {
    const eids = await prisma.eventSubs.findMany({
      select: { event_id: true },
      distinct: 'event_id',
    }).then(v => v.map(e => e.event_id));
    const events = await Promise.all(eids.map(eid => KaiqiuService.getEventInfo(eid)));
    const expiredEvents = events.filter(e => e.isFinished || e.isProcessing);
    const beforeEvents = events.filter(e => !e.isFinished && !e.isProcessing);
    await prisma.eventSubs.deleteMany({
      where: {
        event_id: { in: expiredEvents.map(e => e.eventId) }
      }
    });
    const [requests] = await Promise.all([
      beforeEvents.map(e => KaiqiuService.getMatchDetail(e.eventId, true)),
    ]);
    const details = await Promise.all(requests);
    return details;
  }
}