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

export interface InviteCode {
	id: number;
	code: string;
	tenant_slug: string;
	company_id: number | null;
	role: string;
	max_uses: number | null;
	uses_count: number;
	expires_at: string | null;
	is_active: boolean;
	created_by: string;
	created_at: string;
}

export interface CreateInviteCodeRequest {
	company_id?: number | null;
	role: string;
	max_uses?: number | null;
	expires_at?: string | null;
}

export interface ValidateInviteCodeResponse {
	code: string;
	tenant_slug: string;
	company_id: number | null;
	role: string;
	remaining_uses: number | null;
	expires_at: string | null;
}

export const inviteCodesAPI = {
	async list(companyId: number, includeInactive = false): Promise<InviteCode[]> {
		const params = new URLSearchParams({ company_id: companyId.toString() });
		if (includeInactive) params.set('include_inactive', 'true');
		const response = await api.get<InviteCode[]>(`/v1/core/invite-codes?${params}`);
		if (response.error) throw new Error(response.error);
		return response.data!;
	},

	async create(data: CreateInviteCodeRequest): Promise<InviteCode> {
		const response = await api.post<InviteCode>('/v1/core/invite-codes', data);
		if (response.error) throw new Error(response.error);
		return response.data!;
	},

	async revoke(code: string): Promise<void> {
		const response = await api.delete(`/v1/core/invite-codes/${code}`);
		if (response.error) throw new Error(response.error);
	},

	async validate(code: string): Promise<ValidateInviteCodeResponse> {
		const response = await api.get<ValidateInviteCodeResponse>(
			`/v1/core/invite-codes/validate/${code}`
		);
		if (response.error) throw new Error(response.error);
		return response.data!;
	}
};
