import { db } from '../db/db_index';
import { complaints, users } from '../db/schema';
import { eq, desc, lt } from 'drizzle-orm';

export interface Complaint {
  id: number;
  complaintBody: string;
  userId: number;
  orderId: number | null;
  isResolved: boolean;
  response: string | null;
  createdAt: Date;
  images: string[] | null;
}

export interface ComplaintWithUser extends Complaint {
  userName: string | null;
  userMobile: string | null;
}

export async function getComplaintById(id: number): Promise<Complaint | null> {
  const complaint = await db.query.complaints.findFirst({
    where: eq(complaints.id, id),
  });

  return complaint ?? null;
}

export async function getComplaints(
  cursor?: number,
  limit: number = 20
): Promise<{ complaints: ComplaintWithUser[]; hasMore: boolean }> {
  let whereCondition = cursor ? lt(complaints.id, cursor) : undefined;

  const complaintsData = await db
    .select({
      id: complaints.id,
      complaintBody: complaints.complaintBody,
      userId: complaints.userId,
      orderId: complaints.orderId,
      isResolved: complaints.isResolved,
      response: complaints.response,
      createdAt: complaints.createdAt,
      images: complaints.images,
      userName: users.name,
      userMobile: users.mobile,
    })
    .from(complaints)
    .leftJoin(users, eq(complaints.userId, users.id))
    .where(whereCondition)
    .orderBy(desc(complaints.id))
    .limit(limit + 1);

  const hasMore = complaintsData.length > limit;
  const complaintsToReturn = hasMore ? complaintsData.slice(0, limit) : complaintsData;

  return {
    complaints: complaintsToReturn.map((c) => ({
      id: c.id,
      complaintBody: c.complaintBody,
      userId: c.userId,
      orderId: c.orderId,
      isResolved: c.isResolved,
      response: c.response,
      createdAt: c.createdAt,
      images: c.images as string[],
      userName: c.userName,
      userMobile: c.userMobile,
    })),
    hasMore,
  };
}

export async function resolveComplaint(
  id: number,
  response?: string
): Promise<void> {
  await db
    .update(complaints)
    .set({ isResolved: true, response })
    .where(eq(complaints.id, id));
}
