import { db } from '../config/database.js';
import { emailSignatures } from '../db/schema.js';
import { eq } from 'drizzle-orm';
import { NotFoundError } from '../utils/errors.js';

/**
 * Get signature for a user
 */
export const getSignature = async (userId) => {
  const [signature] = await db
    .select()
    .from(emailSignatures)
    .where(eq(emailSignatures.userId, userId))
    .limit(1);

  return signature || null;
};

/**
 * Create or update signature for a user
 */
export const upsertSignature = async (userId, data) => {
  const existing = await getSignature(userId);

  if (existing) {
    // Update
    const [updated] = await db
      .update(emailSignatures)
      .set({
        fullName: data.fullName || null,
        position: data.position || null,
        phone: data.phone || null,
        email: data.email || null,
        companyName: data.companyName || null,
        website: data.website || null,
        isEnabled: data.isEnabled !== undefined ? data.isEnabled : existing.isEnabled,
        updatedAt: new Date(),
      })
      .where(eq(emailSignatures.userId, userId))
      .returning();

    return updated;
  } else {
    // Create
    const [created] = await db
      .insert(emailSignatures)
      .values({
        userId,
        fullName: data.fullName || null,
        position: data.position || null,
        phone: data.phone || null,
        email: data.email || null,
        companyName: data.companyName || null,
        website: data.website || null,
        isEnabled: data.isEnabled !== undefined ? data.isEnabled : true,
      })
      .returning();

    return created;
  }
};

/**
 * Toggle signature enabled/disabled
 */
export const toggleSignature = async (userId, isEnabled) => {
  const existing = await getSignature(userId);

  if (!existing) {
    throw new NotFoundError('Signature not found');
  }

  const [updated] = await db
    .update(emailSignatures)
    .set({
      isEnabled,
      updatedAt: new Date(),
    })
    .where(eq(emailSignatures.userId, userId))
    .returning();

  return updated;
};

/**
 * Format signature as plain text for email
 */
export const formatSignatureText = (signature) => {
  if (!signature || !signature.isEnabled) {
    return '';
  }

  const lines = [];

  if (signature.fullName) {
    lines.push(signature.fullName);
  }

  const positionLine = [signature.position, signature.companyName]
    .filter(Boolean)
    .join(' | ');
  if (positionLine) {
    lines.push(positionLine);
  }

  if (signature.phone) {
    lines.push(signature.phone);
  }

  if (signature.email) {
    lines.push(signature.email);
  }

  if (signature.website) {
    lines.push(signature.website);
  }

  if (lines.length === 0) {
    return '';
  }

  return '\n\n———\n' + lines.join('\n');
};

/**
 * Delete signature for a user
 */
export const deleteSignature = async (userId) => {
  const existing = await getSignature(userId);

  if (!existing) {
    throw new NotFoundError('Signature not found');
  }

  await db
    .delete(emailSignatures)
    .where(eq(emailSignatures.userId, userId));

  return { message: 'Signature deleted' };
};
