import type { NextFunction, Request, Response } from "express";
import { z } from "zod";

export const validate = (schema: z.ZodSchema) => {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      schema.parse(req.body);
      next();
    } catch (error) {
      if (error instanceof z.ZodError) {
        res.status(400).json({
          success: false,
          error: "Validation failed",
          details: error.errors,
        });
        return;
      }
      next(error);
    }
  };
};

export const loginSchema = z.object({
  email: z.string().email("Invalid email format"),
  password: z.string().min(6, "Password must be at least 6 characters long"),
});

export const registerSchema = z.object({
  username: z.string().min(3, "Username must be at least 3 characters long"),
  email: z.string().email("Invalid email format"),
  password: z.string().min(6, "Password must be at least 6 characters long"),
});

export const createChatRoomSchema = z.object({
  name: z.string().min(1, "Room name is required"),
  description: z.string().optional(),
  memberUsernames: z.array(z.string()).default([]),
});

export const updateUserSchema = z.object({
  username: z.string().min(3, "Username must be at least 3 characters long").optional(),
  email: z.string().email("Invalid email format").optional(),
  password: z.string().min(6, "Password must be at least 6 characters long").optional(),
  avatar: z.string().nullable().optional(),
});

export const updateChatRoomSchema = z.object({
  name: z.string().min(1, "Room name is required"),
  description: z.string().optional(),
});

export const addChatRoomMemberSchema = z.object({
  username: z.string().min(1, "Username is required"),
});

export const removeChatRoomMemberSchema = z.object({
  userId: z.string().min(1, "User ID is required"),
});
