import { z } from 'zod';

export const connectAccountSchema = z.object({
  provider: z.enum(['google', 'outlook', 'custom']),
  emailAddress: z.string().email(),
  smtpHost: z.string().min(1),
  smtpPort: z.number().int().positive(),
  imapHost: z.string().min(1),
  imapPort: z.number().int().positive(),
  username: z.string().min(1),
  password: z.string().min(1),
});

export const toggleAccountSchema = z.object({
  isActive: z.boolean(),
});

export const composeEmailSchema = z
  .object({
    senderType: z.enum(['system', 'user']).default('user'),
    /** Required when senderType=user; ignored otherwise. */
    accountId: z.string().uuid().optional(),
    threadId: z.string().uuid().optional(),
    to: z.array(z.string().email()).min(1),
    cc: z.array(z.string().email()).optional(),
    subject: z.string().min(1),
    bodyHtml: z.string().min(1),
    inReplyToMessageId: z.string().optional(),
    attachments: z
      .array(z.object({ fileId: z.string().uuid(), filename: z.string().optional() }))
      .optional(),
  })
  .refine((d) => d.senderType !== 'user' || Boolean(d.accountId), {
    path: ['accountId'],
    message: 'accountId is required when senderType=user',
  });

export const listThreadsSchema = z.object({
  page: z.coerce.number().int().positive().default(1),
  limit: z.coerce.number().int().positive().max(100).default(20),
  clientId: z.string().uuid().optional(),
});

export type ConnectAccountInput = z.infer<typeof connectAccountSchema>;
export type ToggleAccountInput = z.infer<typeof toggleAccountSchema>;
export type ComposeEmailInput = z.infer<typeof composeEmailSchema>;
export type ListThreadsInput = z.infer<typeof listThreadsSchema>;
