import { emailTemplatesAdapter } from '@/lib/adapters/email-templates';
import { logger } from '@/lib/logger';

export interface CreateEmailTemplateInput {
  name: string;
  subject: string;
  bodyHtml: string;
  createdBy: string;
  isShared?: boolean;
}

export interface UpdateEmailTemplateInput {
  name?: string;
  subject?: string;
  bodyHtml?: string;
  isShared?: boolean;
}

export async function getTemplatesForUser(userId: string) {
  return emailTemplatesAdapter.findMany({
    where: {
      OR: [{ createdBy: userId }, { isShared: true }],
    },
    orderBy: { createdAt: 'desc' },
  });
}

export async function createTemplate(input: CreateEmailTemplateInput) {
  return emailTemplatesAdapter.create({
    data: {
      name: input.name,
      subject: input.subject,
      bodyHtml: input.bodyHtml,
      createdBy: input.createdBy,
      isShared: input.isShared ?? false,
      createdAt: new Date(),
      updatedAt: new Date(),
    },
  });
}

export async function getTemplate(templateId: string) {
  return emailTemplatesAdapter.findUnique({
    where: { id: templateId },
  });
}

export async function updateTemplate(
  templateId: string,
  updates: UpdateEmailTemplateInput
) {
  return emailTemplatesAdapter.update({
    where: { id: templateId },
    data: {
      ...updates,
      updatedAt: new Date(),
    },
  });
}

export async function deleteTemplate(templateId: string) {
  try {
    await emailTemplatesAdapter.delete({ where: { id: templateId } });
  } catch (error) {
    logger.error('Failed to delete email template', { templateId, error });
    throw error;
  }
}

export async function canUserModifyTemplate(
  templateId: string,
  userId: string,
  isAdmin: boolean
): Promise<boolean> {
  if (isAdmin) return true;

  const template = await emailTemplatesAdapter.findUnique({
    where: { id: templateId },
    select: { createdBy: true },
  });

  return template?.createdBy === userId;
}
