import client from './client';
import type { PaginatedResponse } from './types';

export interface MessageInfo {
  id: string;
  tenant_id: string;
  template_id?: string;
  sender_id?: string;
  sender_type: string;
  recipient_id: string;
  recipient_type: string;
  title: string;
  body: string;
  priority: string;
  business_type?: string;
  business_id?: string;
  is_read: boolean;
  read_at?: string;
  is_archived: boolean;
  status: string;
  sent_at?: string;
  created_at: string;
  updated_at: string;
}

export interface SendMessageRequest {
  title: string;
  body: string;
  recipient_id: string;
  recipient_type?: string;
  priority?: string;
  template_id?: string;
  business_type?: string;
  business_id?: string;
}

export interface MessageQuery {
  page?: number;
  page_size?: number;
  is_read?: boolean;
  priority?: string;
  business_type?: string;
  status?: string;
}

export async function listMessages(query: MessageQuery = {}) {
  const { data } = await client.get<{ success: boolean; data: PaginatedResponse<MessageInfo> }>(
    '/messages',
    { params: { page: query.page ?? 1, page_size: query.page_size ?? 20, ...query } },
  );
  return data.data;
}

export async function getUnreadCount() {
  const { data } = await client.get<{ success: boolean; data: { count: number } }>(
    '/messages/unread-count',
  );
  return data.data;
}

export async function markRead(id: string) {
  const { data } = await client.put<{ success: boolean }>(
    `/messages/${id}/read`,
  );
  return data;
}

export async function markAllRead() {
  const { data } = await client.put<{ success: boolean }>(
    '/messages/read-all',
  );
  return data;
}

export async function deleteMessage(id: string) {
  const { data } = await client.delete<{ success: boolean }>(
    `/messages/${id}`,
  );
  return data;
}

export async function sendMessage(req: SendMessageRequest) {
  const { data } = await client.post<{ success: boolean; data: MessageInfo }>(
    '/messages',
    req,
  );
  return data.data;
}

export interface SubscriptionUpdateReq {
  dnd_enabled: boolean;
  dnd_start?: string;
  dnd_end?: string;
}

export async function updateSubscription(req: SubscriptionUpdateReq) {
  await client.put('/message-subscriptions', req);
}
