import { trpc } from '../api/trpc-client';

export interface ProtonMailMessage {
  id: string;
  subject: string;
  sender: { email: string; name?: string };
  recipients: Array<{ email: string; name?: string }>;
  body: string;
  attachments?: ProtonMailAttachment[];
  timestamp: string;
  read: boolean;
}

export interface ProtonMailAttachment {
  id: string;
  filename: string;
  mimeType: string;
  size: number;
  downloadUrl: string;
}

export interface ProtonMailContact {
  id: string;
  email: string;
  name: string;
  phone?: string;
  organization?: string;
}

export class ProtonMailClient {
  constructor(private baseUrl: string = `${(import.meta as any).env?.VITE_API_URL || 'http://localhost:8080'}`) {}

  async getMessages(folder?: string): Promise<ProtonMailMessage[]> {
    const result = await trpc.mail.messages.query({ folder });
    return result;
  }

  async getMessage(messageId: string): Promise<ProtonMailMessage> {
    const result = await trpc.mail.message.query({ messageId });
    return result;
  }

  async sendMessage(
    to: string[],
    subject: string,
    body: string,
    attachments?: ProtonMailAttachment[]
  ): Promise<ProtonMailMessage> {
    const result = await trpc.mail.send.mutate({
      to,
      subject,
      body,
      attachments,
    });
    return result;
  }

  async getContact(email: string): Promise<ProtonMailContact | null> {
    const result = await trpc.mail.contact.query({ email });
    return result;
  }

  async getContacts(): Promise<ProtonMailContact[]> {
    const result = await trpc.mail.contacts.query({});
    return result;
  }

  async addContact(contact: Omit<ProtonMailContact, 'id'>): Promise<ProtonMailContact> {
    const result = await trpc.mail.addContact.mutate(contact);
    return result;
  }

  async getAttachment(attachmentId: string): Promise<ProtonMailAttachment> {
    const result = await trpc.mail.attachment.query({ attachmentId });
    return result;
  }

  async downloadAttachment(attachmentId: string): Promise<Blob> {
    const result = await trpc.mail.attachmentDownload.query({ attachmentId });
    return result as unknown as Blob;
  }
}

export const protonMail = new ProtonMailClient();
