import { router, protectedProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod';
import { db } from '@/src/db/db_index'
import { complaints, users } from '@/src/db/schema'
import { eq, desc, lt, and } from 'drizzle-orm';
import { generateSignedUrlsFromS3Urls } from '@/src/lib/s3-client'

export const complaintRouter = router({
  getAll: protectedProcedure
    .input(z.object({
      cursor: z.number().optional(),
      limit: z.number().default(20),
    }))
    .query(async ({ input }) => {
      const { cursor, limit } = input;

      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,
          createdAt: complaints.createdAt,
          userName: users.name,
          userMobile: users.mobile,
          images: complaints.images,
        })
        .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;

      const complaintsWithSignedImages = await Promise.all(
        complaintsToReturn.map(async (c) => {
          const signedImages = c.images
            ? await generateSignedUrlsFromS3Urls(c.images as string[])
            : [];

          return {
            id: c.id,
            text: c.complaintBody,
            userId: c.userId,
            userName: c.userName,
            userMobile: c.userMobile,
            orderId: c.orderId,
            status: c.isResolved ? 'resolved' : 'pending',
            createdAt: c.createdAt,
            images: signedImages,
          };
        })
      );

      return {
        complaints: complaintsWithSignedImages,
        nextCursor: hasMore
          ? complaintsToReturn[complaintsToReturn.length - 1].id
          : undefined,
      };
    }),

  resolve: protectedProcedure
    .input(z.object({ id: z.string(), response: z.string().optional() }))
    .mutation(async ({ input }) => {
      await db
        .update(complaints)
        .set({ isResolved: true, response: input.response })
        .where(eq(complaints.id, parseInt(input.id)));

      return { message: 'Complaint resolved successfully' };
    }),
});