import { router, protectedProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod'
import {
  getUserComplaints as getUserComplaintsInDb,
  createUserComplaint as createUserComplaintInDb,
} from '@/src/dbService'
import type { UserComplaintsResponse, UserRaiseComplaintResponse } from '@packages/shared'

export const complaintRouter = router({
  getAll: protectedProcedure
    .query(async ({ ctx }): Promise<UserComplaintsResponse> => {
      const userId = ctx.user.userId;

      const userComplaints = await getUserComplaintsInDb(userId)

      /*
      // Old implementation - direct DB queries:
      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(complaints.createdAt);

      return {
        complaints: userComplaints.map(c => ({
          id: c.id,
          complaintBody: c.complaintBody,
          response: c.response,
          isResolved: c.isResolved,
          createdAt: c.createdAt,
          orderId: c.orderId,
        })),
      };
      */

      return {
        complaints: userComplaints,
      }
    }),

  raise: protectedProcedure
    .input(z.object({
      orderId: z.string().optional(),
      complaintBody: z.string().min(1, 'Complaint body is required'),
      imageUrls: z.array(z.string()).optional(),
    }))
    .mutation(async ({ input, ctx }): Promise<UserRaiseComplaintResponse> => {
      const userId = ctx.user.userId;
      const { orderId, complaintBody, imageUrls } = input;

      let orderIdNum: number | null = null;

      if (orderId) {
        const readableIdMatch = orderId.match(/^ORD(\d+)$/);
        if (readableIdMatch) {
          orderIdNum = parseInt(readableIdMatch[1]);
        }
      }

      await createUserComplaintInDb(
        userId,
        orderIdNum,
        complaintBody.trim(),
        imageUrls && imageUrls.length > 0 ? imageUrls : null
      )

      /*
      // Old implementation - direct DB query:
      await db.insert(complaints).values({
        userId,
        orderId: orderIdNum,
        complaintBody: complaintBody.trim(),
      });
      */

      return { success: true, message: 'Complaint raised successfully' }
    }),
});
