import { db } from '../config/database.js';
import { emailAccounts } from '../db/schema.js';
import { eq, and } from 'drizzle-orm';
import { NotFoundError, BadRequestError } from './errors.js';

export const getEmailAccountById = async (accountId, userId = null) => {
  const conditions = [eq(emailAccounts.id, accountId)];
  if (userId) {
    conditions.push(eq(emailAccounts.userId, userId));
  }

  const [account] = await db
    .select()
    .from(emailAccounts)
    .where(and(...conditions))
    .limit(1);

  if (!account) {
    throw new NotFoundError('Email account not found');
  }

  return account;
};

export const getActiveEmailAccount = async (accountId, userId = null) => {
  const account = await getEmailAccountById(accountId, userId);
  if (!account.isActive) {
    throw new BadRequestError('Email account is not active');
  }
  return account;
};
