import { signIn } from 'next-auth/react';
import { LoginFormData, RegisterFormData } from '@/src/types/auth';
import { NextResponse } from 'next/server';

export class AuthService {
  static async login(values: LoginFormData) {
    const { emailOrUsername, password } = values;
    const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailOrUsername);

    const result = await signIn('credentials', {
      redirect: false,
      [isEmail ? 'email' : 'username']: emailOrUsername,
      password,
    });

    if (!result?.ok) {
      return NextResponse.json(
        {
          ok: false,
          error: result?.error,
          message: 'Check your credentials',
        },
        { status: 400 }
      );
    }

    return NextResponse.json({ ok: result?.ok, message: 'Login successful' });
  }

  static async register(values: RegisterFormData, invite?: string | null) {
    const response = await fetch('/api/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ ...values, invite }),
    });

    const data = await response.json();

    if (!response.ok) {
      return NextResponse.json(
        {
          ok: false,
          message: data.message,
        },
        { status: 400 }
      );
    }

    const result = await signIn('credentials', {
      email: values.email,
      password: values.password,
      redirect: false,
    });

    return NextResponse.json({
      ...result,
      ok: !result?.error,
      message: 'Registration successful',
    });
  }

  static async forgotPassword(email: string) {
    return await fetch('/api/auth/reset', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email }),
    });
  }

  static async resetPassword(token: string, newPassword: string) {
    const response = await fetch(`/api/auth/reset/${token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ token, newPassword }),
    });

    if (!response.ok) {
      throw new Error('Failed to reset password');
    }

    return response.json();
  }

  static async registerWithInvitation(data: {
    email: string;
    password: string;
    username: string;
    token: string;
    portfolioId: string;
  }) {
    return await fetch(`/api/auth/register/${data.token}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: data.email,
        password: data.password,
        username: data.username,
        portfolioId: data.portfolioId,
      }),
    });
  }
}
