import {
  BotPresenceConfigPatchSchema,
  BotPresenceConfigSchema,
  PRESENCE_REDIS_KEY,
  type BotPresenceConfig
} from '@nexumi/shared';
import { prisma } from './prisma';
import { getPresenceQueue } from './queues';
import { redis } from './redis';

function mapRow(row: {
  status: string;
  activityType: string;
  activityText: string;
  rotatingMessages: unknown;
  maintenanceMode: boolean;
  maintenanceMessage: string | null;
}): BotPresenceConfig {
  const rotating = Array.isArray(row.rotatingMessages)
    ? row.rotatingMessages.filter((item): item is string => typeof item === 'string')
    : [];
  return BotPresenceConfigSchema.parse({
    status: row.status,
    activityType: row.activityType,
    activityText: row.activityText,
    rotatingMessages: rotating,
    maintenanceMode: row.maintenanceMode,
    maintenanceMessage: row.maintenanceMessage
  });
}

export async function getPresenceConfig(): Promise<BotPresenceConfig> {
  const row = await prisma.botPresenceConfig.upsert({
    where: { id: 'singleton' },
    create: { id: 'singleton' },
    update: {}
  });
  return mapRow(row);
}

export async function updatePresenceConfig(patch: unknown): Promise<BotPresenceConfig> {
  const data = BotPresenceConfigPatchSchema.parse(patch);
  const current = await getPresenceConfig();
  const next = { ...current, ...data };
  const row = await prisma.botPresenceConfig.upsert({
    where: { id: 'singleton' },
    create: {
      id: 'singleton',
      status: next.status,
      activityType: next.activityType,
      activityText: next.activityText,
      rotatingMessages: next.rotatingMessages,
      maintenanceMode: next.maintenanceMode,
      maintenanceMessage: next.maintenanceMessage
    },
    update: {
      status: next.status,
      activityType: next.activityType,
      activityText: next.activityText,
      rotatingMessages: next.rotatingMessages,
      maintenanceMode: next.maintenanceMode,
      maintenanceMessage: next.maintenanceMessage
    }
  });
  const mapped = mapRow(row);
  await redis.set(PRESENCE_REDIS_KEY, JSON.stringify(mapped));
  await getPresenceQueue().add(
    'presenceRefresh',
    {},
    {
      removeOnComplete: 5,
      removeOnFail: 5
    }
  );
  return mapped;
}
