import { protectedProcedure } from '../trpc-index';
import { z } from 'zod';
import { db } from '../../db/db_index';
import { users, complaints } from '../../db/schema';
import { eq } from 'drizzle-orm';
import { ApiError } from '../../lib/api-error';

async function createUserByMobile(mobile: string): Promise<typeof users.$inferSelect> {
  // Clean mobile number (remove non-digits)
  const cleanMobile = mobile.replace(/\D/g, '');

  // Validate: exactly 10 digits
  if (cleanMobile.length !== 10) {
    throw new ApiError('Mobile number must be exactly 10 digits', 400);
  }

  // Check if user already exists
  const [existingUser] = await db
    .select()
    .from(users)
    .where(eq(users.mobile, cleanMobile))
    .limit(1);

  if (existingUser) {
    throw new ApiError('User with this mobile number already exists', 409);
  }

  // Create user
  const [newUser] = await db
    .insert(users)
    .values({
      name: null,
      email: null,
      mobile: cleanMobile,
    })
    .returning();

  return newUser;
}

export const userRouter = {
  createUserByMobile: protectedProcedure
    .input(z.object({
      mobile: z.string().min(1, 'Mobile number is required'),
    }))
    .mutation(async ({ input }) => {
      const newUser = await createUserByMobile(input.mobile);

      return {
        success: true,
        data: newUser,
      };
    }),

  getEssentials: protectedProcedure
    .query(async () => {
      const count = await db.$count(complaints, eq(complaints.isResolved, false));
      
      return {
        unresolvedComplaints: count || 0,
      };
    }),
};