import { db } from '../db/db_index'
import { complaints } from '../db/schema'
import { asc, eq } from 'drizzle-orm'
import type { InferSelectModel } from 'drizzle-orm'
import type { UserComplaint } from '@packages/shared'

type ComplaintRow = InferSelectModel<typeof complaints>

export async function getUserComplaints(userId: number): Promise<UserComplaint[]> {
  const userComplaints = await db
    .select({
      id: complaints.id,
      complaintBody: complaints.complaintBody,
      response: complaints.response,
      isResolved: complaints.isResolved,
      createdAt: complaints.createdAt,
      orderId: complaints.orderId,
    })
    .from(complaints)
    .where(eq(complaints.userId, userId))
    .orderBy(asc(complaints.createdAt))

  return userComplaints.map((complaint) => ({
    id: complaint.id,
    complaintBody: complaint.complaintBody,
    response: complaint.response ?? null,
    isResolved: complaint.isResolved,
    createdAt: complaint.createdAt,
    orderId: complaint.orderId ?? null,
  }))
}

export async function createComplaint(
  userId: number,
  orderId: number | null,
  complaintBody: string,
  images?: string[] | null
): Promise<void> {
  await db.insert(complaints).values({
    userId,
    orderId,
    complaintBody,
    images: images || null,
  })
}
