import { getApiBaseUrl } from '$lib/api';
import { authenticatedFetch } from '$lib/auth';

export interface TeacherSubmission {
	id: string | null;
	studentId: string;
	studentName: string;
	status: 'draft' | 'submitted' | 'late' | 'not_submitted';
	submittedAt: string | null;
	createdAt: string | null;
}

export interface TeacherSubmissionDetail {
	id: string;
	studentId: string;
	studentName: string;
	responseHtml: string | null;
	status: 'draft' | 'submitted' | 'late';
	submittedAt: string | null;
	createdAt: string;
	attachments: {
		id: string;
		filename: string;
		fileSize: number;
		mimeType: string;
	}[];
}

export interface SubmissionStats {
	totalStudents: number;
	submittedCount: number;
	missingStudents: { id: string; name: string }[];
}

/**
 * Récupère la liste des rendus pour un devoir.
 */
export async function fetchSubmissions(homeworkId: string): Promise<TeacherSubmission[]> {
	const apiUrl = getApiBaseUrl();
	const response = await authenticatedFetch(`${apiUrl}/homework/${homeworkId}/submissions`);

	if (!response.ok) {
		throw new Error(`Erreur lors du chargement des rendus (${response.status})`);
	}

	const json = await response.json();
	return json.data ?? [];
}

/**
 * Récupère le détail d'un rendu.
 */
export async function fetchSubmissionDetail(
	homeworkId: string,
	submissionId: string
): Promise<TeacherSubmissionDetail> {
	const apiUrl = getApiBaseUrl();
	const response = await authenticatedFetch(
		`${apiUrl}/homework/${homeworkId}/submissions/${submissionId}`
	);

	if (!response.ok) {
		throw new Error(`Erreur lors du chargement du rendu (${response.status})`);
	}

	const json = await response.json();
	return json.data;
}

/**
 * Récupère les statistiques de rendus pour un devoir.
 */
export async function fetchSubmissionStats(homeworkId: string): Promise<SubmissionStats> {
	const apiUrl = getApiBaseUrl();
	const response = await authenticatedFetch(
		`${apiUrl}/homework/${homeworkId}/submissions/stats`
	);

	if (!response.ok) {
		throw new Error(`Erreur lors du chargement des statistiques (${response.status})`);
	}

	const json = await response.json();
	return json.data;
}

/**
 * Retourne l'URL de téléchargement d'une pièce jointe de rendu.
 */
export function getSubmissionAttachmentUrl(
	homeworkId: string,
	submissionId: string,
	attachmentId: string
): string {
	const apiUrl = getApiBaseUrl();
	return `${apiUrl}/homework/${homeworkId}/submissions/${submissionId}/attachments/${attachmentId}`;
}
