import {
  ComplexMembersError,
  inviteComplexUser,
} from '@/modules/complex/services/complex-members.service';
import type { AppContext } from '@/types/hono';
import type { InviteComplexUserInput } from '@repo/api-contract';
import { z } from 'zod';

const complexParamsSchema = z.object({
  id: z.uuid(),
});

type InviteComplexUserHandlerDeps = {
  inviteComplexUser: typeof inviteComplexUser;
  ComplexMembersError: typeof ComplexMembersError;
};

export function createInviteComplexUserHandler(
  deps: InviteComplexUserHandlerDeps = {
    inviteComplexUser,
    ComplexMembersError,
  }
) {
  return async function inviteComplexUserHandler(c: AppContext) {
    const user = c.get('user');
    const params = complexParamsSchema.parse(c.req.param());
    const payload = c.req.valid('json' as never) as InviteComplexUserInput;

    try {
      const result = await deps.inviteComplexUser(user.id, params.id, payload);
      return c.json(result, 201);
    } catch (error) {
      if (error instanceof deps.ComplexMembersError) {
        return c.json(
          { message: error.message },
          {
            status: error.status,
          }
        );
      }

      throw error;
    }
  };
}

export const inviteComplexUserHandler = createInviteComplexUserHandler();
