import { apiFetch } from './api';

export interface AuthUser {
    _id: string;
    username: string;
    dispName: string;
    email: string;
    roles: string[];
    active: boolean;
    bloodType?: string;
    height?: number;
    weight?: number;
    allergies?: string[];
    residentCountry?: string;
    residentCity?: string;
    sharingInfo?: string[];
    specialty?: string;
    hospital?: string;
    department?: string;
    title?: string;
    phoneNumber?: string;
}

export interface LoginResponse {
    accessToken: string;
    tokenType: string;
    expiresIn: number;
    user: AuthUser;
}

/**
 * Login with username/email and password.
 */
export async function login(identifier: string, password: string): Promise<LoginResponse> {
    const isEmail = identifier.includes('@');
    const body = isEmail
        ? { email: identifier, password }
        : { username: identifier, password };

    const res = await fetch(
        `${import.meta.env.VITE_API_URL || '/api'}/auth/login`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        },
    );

    if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || 'Login failed');
    }

    return res.json();
}

/**
 * Verify the current token.
 */
export async function verifyToken(): Promise<{ valid: boolean; payload: Record<string, unknown> }> {
    return apiFetch('/auth/verify');
}

/**
 * Register a new user account.
 */
export async function register(data: {
    username: string;
    email: string;
    password: string;
    dispName: string;
    role: string;
}): Promise<LoginResponse> {
    const res = await fetch(
        `${import.meta.env.VITE_API_URL || '/api'}/auth/register`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
        },
    );

    if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error || 'Registration failed');
    }

    return res.json();
}

/**
 * Change the authenticated user's password.
 */
export async function changePassword(currentPassword: string, newPassword: string): Promise<void> {
    await apiFetch('/auth/change-password', {
        method: 'PATCH',
        body: JSON.stringify({ currentPassword, newPassword }),
    });
}

/**
 * Update the authenticated user's profile (name, email, etc.).
 */
export async function updateProfile(userId: string, updates: Record<string, unknown>): Promise<AuthUser> {
    return apiFetch(`/users/${userId}`, {
        method: 'PATCH',
        body: JSON.stringify(updates),
    });
}

/**
 * Delete the authenticated user's account.
 */
export async function deleteAccount(userId: string): Promise<void> {
    await apiFetch(`/users/${userId}`, {
        method: 'DELETE',
    });
}
