import { eq, and } from 'drizzle-orm';
import { db } from '../db';
import { emailAccounts } from './schema';
import type { EmailAccountInsert, EmailAccountSelect } from '../types';

export async function getEmailAccounts(userId: number): Promise<EmailAccountSelect[]> {
  return db.select().from(emailAccounts).where(eq(emailAccounts.userId, userId));
}

export async function getEmailAccount(id: number): Promise<EmailAccountSelect | undefined> {
  const [row] = await db.select().from(emailAccounts).where(eq(emailAccounts.id, id));
  return row;
}

export async function createEmailAccount(params: EmailAccountInsert): Promise<EmailAccountSelect> {
  const [row] = await db.insert(emailAccounts).values(params).returning();
  return row!;
}

export async function deleteEmailAccount(id: number, userId: number): Promise<boolean> {
  const [row] = await db
    .delete(emailAccounts)
    .where(and(eq(emailAccounts.id, id), eq(emailAccounts.userId, userId)))
    .returning({ id: emailAccounts.id });
  return !!row;
}

export async function updateEmailAccountStatus(id: number, status: string): Promise<void> {
  await db.update(emailAccounts).set({ status }).where(eq(emailAccounts.id, id));
}

export async function updateEmailAccountSyncMeta(id: number, syncMeta: Record<string, unknown>): Promise<void> {
  await db.update(emailAccounts).set({ syncMeta }).where(eq(emailAccounts.id, id));
}

export async function getAllSyncedAccounts(): Promise<EmailAccountSelect[]> {
  return db
    .select()
    .from(emailAccounts)
    .where(and(eq(emailAccounts.status, 'synced'), eq(emailAccounts.enabled, true)));
}
