import { z } from 'zod';
import { publicProcedure, router } from '../trpc';
import { signIn, signOut, resetPassword } from '@crafted/auth';
import { registerUserUseCase } from '../use-cases';
import * as authService from '@crafted/services';

export const authRouter = router({
  register: publicProcedure
    .input(
      z.object({
        email: z.string().email(),
        password: z.string().min(8),
        name: z.string().optional(),
      })
    )
    .mutation(async ({ input }) => {
      const result = await registerUserUseCase.execute(input);

      if (result.isFailure()) {
        throw new Error(result.getError());
      }

      const output = result.getValue();

      return {
        user: output.user.toPlainObject(),
        supabaseUserId: output.supabaseUserId,
      };
    }),

  login: publicProcedure
    .input(
      z.object({
        email: z.string().email(),
        password: z.string(),
      })
    )
    .mutation(async ({ input }) => {
      const data = await signIn(input);
      return {
        user: data.user,
        session: data.session,
      };
    }),

  logout: publicProcedure.mutation(async () => {
    await signOut();
    return { success: true };
  }),

  me: publicProcedure.query(async () => {
    return await authService.getUser();
  }),

  resetPassword: publicProcedure
    .input(
      z.object({
        email: z.string().email(),
      })
    )
    .mutation(async ({ input }) => {
      await resetPassword(input.email);
      return { success: true };
    }),
});
