/**
 * Cliente API para gestión de usuarios
 */

import { api } from '$lib/api';

export interface User {
	id: string;
	username: string;
	email: string;
	first_name: string;
	last_name: string;
	enabled: boolean;
	email_verified: boolean;
	created_timestamp?: number;
	role?: string;
}

export interface UserStats {
	total_users: number;
	active_users: number;
	inactive_users: number;
	max_users_allowed: number;
	users_available: number;
	usage_percentage: number;
}

export interface UserListResponse {
	users: User[];
	total: number;
	page: number;
	page_size: number;
	total_pages: number;
}

export interface CreateUserRequest {
	email: string;
	username: string;
	first_name: string;
	last_name: string;
	password: string;
	role?: string;
	enabled?: boolean;
	email_verified?: boolean;
}

export interface UpdateUserRequest {
	first_name?: string;
	last_name?: string;
	email?: string;
	enabled?: boolean;
	email_verified?: boolean;
	role?: string;
}

export interface ChangePasswordRequest {
	password: string;
	temporary?: boolean;
}

export interface InviteUserRequest {
	email: string;
	company_id: number;
	role_id: number;
}

export interface InviteUserResponse {
	id: number;
	email: string;
	role: string;
	expires_at: string;
	invite_url: string;
	created_at: string;
}

export const usersAPI = {
	/**
	 * Obtiene estadísticas de usuarios del tenant
	 */
	async getStats(companyId: number): Promise<UserStats> {
		const response = await api.get<UserStats>(`/v1/core/users/stats?company_id=${companyId}`);
		if (response.error) {
			throw new Error(response.error);
		}
		return response.data!;
	},

	/**
	 * Lista usuarios del tenant con paginación
	 */
	async list(companyId: number, params?: {
		page?: number;
		page_size?: number;
		search?: string;
	}): Promise<UserListResponse> {
		const queryParams = new URLSearchParams();
		queryParams.set('company_id', companyId.toString());
		if (params?.page) queryParams.set('page', params.page.toString());
		if (params?.page_size) queryParams.set('page_size', params.page_size.toString());
		if (params?.search) queryParams.set('search', params.search);

		const endpoint = `/v1/core/users/?${queryParams}`;
		const response = await api.get<UserListResponse>(endpoint);
		if (response.error) {
			throw new Error(response.error);
		}
		return response.data!;
	},

	/**
	 * Obtiene un usuario específico
	 */
	async get(userId: string, companyId: number): Promise<User> {
		const response = await api.get<User>(`/v1/core/users/${userId}?company_id=${companyId}`);
		if (response.error) {
			throw new Error(response.error);
		}
		return response.data!;
	},

	/**
	 * Crea un nuevo usuario
	 */
	async create(data: CreateUserRequest, companyId: number): Promise<User> {
		const response = await api.post<User>(`/v1/core/users/?company_id=${companyId}`, data);
		if (response.error) {
			throw new Error(response.error);
		}
		return response.data!;
	},

	/**
	 * Actualiza un usuario existente
	 */
	async update(userId: string, data: UpdateUserRequest, companyId: number): Promise<User> {
		const response = await api.put<User>(`/v1/core/users/${userId}?company_id=${companyId}`, data);
		if (response.error) {
			throw new Error(response.error);
		}
		return response.data!;
	},

	/**
	 * Retorna en cuántos tenants está registrado el usuario.
	 */
	async getTenantCount(userId: string, companyId: number): Promise<number> {
		const response = await api.get<{ tenant_count: number }>(
			`/v1/core/users/${userId}/tenant-count?company_id=${companyId}`
		);
		if (response.error) {
			throw new Error(response.error);
		}
		return response.data!.tenant_count;
	},

	/**
	 * Elimina un usuario
	 */
	async delete(
		userId: string,
		companyId: number,
		softDelete: boolean = true,
		scope: 'current' | 'all' = 'current'
	): Promise<void> {
		const queryParams = new URLSearchParams();
		queryParams.set('company_id', companyId.toString());
		queryParams.set('soft_delete', softDelete.toString());
		queryParams.set('scope', scope);

		const response = await api.delete(`/v1/core/users/${userId}?${queryParams}`);
		if (response.error) {
			throw new Error(response.error);
		}
	},

	/**
	 * Cambia la contraseña de un usuario
	 */
	async changePassword(userId: string, data: ChangePasswordRequest, companyId: number): Promise<void> {
		const response = await api.post(`/v1/core/users/${userId}/change-password?company_id=${companyId}`, data);
		if (response.error) {
			throw new Error(response.error);
		}
	},

	/**
	 * Genera un token de invitación y envía email al usuario
	 */
	async invite(data: InviteUserRequest): Promise<InviteUserResponse> {
		const response = await api.post<InviteUserResponse>('/v1/core/invites', data);
		if (response.error) {
			throw new Error(response.error);
		}
		return response.data!;
	}
};
