import { prisma } from '../../config/database';
import { logger } from '../../utils/logger';
import { AppError } from '../../middleware/error-handler';
import type { BridgeSocialLinksInput } from './social-link-bridge.schemas';

export const socialLinkBridgeService = {
  async sync(input: BridgeSocialLinksInput): Promise<{
    created: number;
    updated: number;
  }> {
    const email = input.email.trim().toLowerCase();
    const user = await prisma.user.findUnique({
      where: { email },
      select: { id: true },
    });
    if (!user) {
      throw new AppError(404, 'No cmlite user for this email', 'NO_CMLITE_USER');
    }

    const top = await prisma.userSocialLink.findFirst({
      where: { userId: user.id },
      orderBy: { position: 'desc' },
      select: { position: true },
    });
    let nextPosition = (top?.position ?? -1) + 1;

    let created = 0;
    let updated = 0;
    for (const link of input.links) {
      const existing = await prisma.userSocialLink.findUnique({
        where: { userId_platform: { userId: user.id, platform: link.platform } },
      });
      if (existing) {
        await prisma.userSocialLink.update({
          where: { id: existing.id },
          data: { url: link.url, displayName: link.displayName ?? null },
        });
        updated++;
      } else {
        await prisma.userSocialLink.create({
          data: {
            userId: user.id,
            platform: link.platform,
            url: link.url,
            displayName: link.displayName ?? null,
            position: nextPosition++,
          },
        });
        created++;
      }
    }

    logger.info('Synced JSN social links to cmlite', {
      userId: user.id,
      email,
      created,
      updated,
    });

    return { created, updated };
  },
};
