// routes/api/retrieve/messages.ts import { define } from "../../../utils.ts"; import { getConversation, getMessageById, getMessagesByLease, getMessagesByUser, getMessageStatsByLease, getUnreadCount, getUnreadMessages, } from "../../../services/messageService.ts"; import { SessionCookie } from "../../auth/callback.ts"; export const handler = define.handlers({ async GET(ctx) { try { const stateData: SessionCookie = ctx.state.data; const { user_id } = stateData; const url = new URL(ctx.req.url); const lease_id = url.searchParams.get("lease_id"); const message_id = url.searchParams.get("id"); const other_user_id = url.searchParams.get("other_user_id"); const unread_only = url.searchParams.get("unread_only") === "true"; const stats_only = url.searchParams.get("stats_only") === "true"; const count_only = url.searchParams.get("count_only") === "true"; let result; if (message_id) { // Get specific message result = await getMessageById(message_id); return new Response( JSON.stringify({ success: true, message: result, }), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } else if (count_only) { // Get unread count for user result = await getUnreadCount(user_id); return new Response( JSON.stringify({ success: true, unread_count: result, }), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } else if (lease_id && stats_only) { // Get message statistics for lease result = await getMessageStatsByLease(lease_id); return new Response( JSON.stringify({ success: true, stats: result, }), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } else if (lease_id && other_user_id) { // Get conversation between two users for a lease result = await getConversation(lease_id, user_id, other_user_id); } else if (lease_id) { // Get all messages for a lease result = await getMessagesByLease(lease_id); } else if (unread_only) { // Get unread messages for user result = await getUnreadMessages(user_id); } else { // Get all messages for user result = await getMessagesByUser(user_id); } return new Response( JSON.stringify({ success: true, messages: result, }), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } catch (e) { return new Response(JSON.stringify({ error: e }), { status: 500, headers: { "Content-Type": "application/json" }, }); } }, });