import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
import { User } from '../../models/user.model';

export interface LoginResponse {
  token: string;
  user: User;
}

export type AuthMeResponse = User & { token?: string };

export interface InviteDetails {
  teamId: number;
  teamName: string;
  playerId: number;
  playerName: string;
}

export interface RegistrationRequest {
  email: string;
  password: string;
  firstName: string;
  lastName: string;
  linkPlayerId: number;
}

export interface CreateInviteRequest extends InviteDetails {}

export interface UpdateProfileRequest {
  firstName?: string;
  lastName?: string;
  oldPassword?: string;
  password?: string;
}

@Injectable({ providedIn: 'root' })
export class AuthApi {
  private readonly http = inject(HttpClient);
  private readonly baseUrl = `${environment.apiUrl}auth`;

  login(email: string, password: string): Observable<LoginResponse> {
    return this.http.post<LoginResponse>(`${this.baseUrl}/email/login`, { email, password });
  }

  me(): Observable<AuthMeResponse> {
    return this.http.get<AuthMeResponse>(`${this.baseUrl}/me`);
  }

  verifyInvite(token: string): Observable<InviteDetails> {
    return this.http.post<InviteDetails>(`${this.baseUrl}/verify-invite`, { token });
  }

  register(request: RegistrationRequest): Observable<void> {
    return this.http.post<void>(`${this.baseUrl}/email/register`, request);
  }

  forgotPassword(email: string): Observable<void> {
    return this.http.post<void>(`${this.baseUrl}/forgot/password`, { email });
  }

  resetPassword(hash: string, password: string): Observable<void> {
    return this.http.post<void>(`${this.baseUrl}/reset/password`, { hash, password });
  }

  createInvite(request: CreateInviteRequest): Observable<{ token: string }> {
    return this.http.post<{ token: string }>(`${this.baseUrl}/invite`, request);
  }

  updateProfile(request: UpdateProfileRequest): Observable<User> {
    return this.http.patch<User>(`${this.baseUrl}/me`, request);
  }
}
