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

export interface StudentHomework {
	id: string;
	subjectId: string;
	subjectName: string;
	subjectColor: string | null;
	teacherId: string;
	teacherName: string;
	title: string;
	description: string | null;
	dueDate: string;
	createdAt: string;
	hasAttachments: boolean;
	submissionStatus: 'draft' | 'submitted' | 'late' | null;
}

export interface HomeworkAttachment {
	id: string;
	filename: string;
	fileSize: number;
	mimeType: string;
}

export interface StudentHomeworkDetail {
	id: string;
	subjectId: string;
	subjectName: string;
	subjectColor: string | null;
	teacherId: string;
	teacherName: string;
	title: string;
	description: string | null;
	dueDate: string;
	createdAt: string;
	attachments: HomeworkAttachment[];
}

export interface HomeworkSubmission {
	id: string;
	homeworkId: string;
	studentId: string;
	responseHtml: string | null;
	status: 'draft' | 'submitted' | 'late';
	submittedAt: string | null;
	createdAt: string;
	updatedAt: string;
	attachments?: HomeworkAttachment[];
}

/**
 * Récupère la liste des devoirs pour l'élève connecté.
 */
export async function fetchStudentHomework(subjectId?: string): Promise<StudentHomework[]> {
	const apiUrl = getApiBaseUrl();
	const params = subjectId ? `?subjectId=${encodeURIComponent(subjectId)}` : '';
	const response = await authenticatedFetch(`${apiUrl}/me/homework${params}`);

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

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

/**
 * Récupère le détail d'un devoir.
 */
export async function fetchHomeworkDetail(homeworkId: string): Promise<StudentHomeworkDetail> {
	const apiUrl = getApiBaseUrl();
	const response = await authenticatedFetch(`${apiUrl}/me/homework/${homeworkId}`);

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

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

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

/**
 * Récupère le rendu de l'élève pour un devoir (ou null si aucun brouillon).
 */
export async function fetchSubmission(homeworkId: string): Promise<HomeworkSubmission | null> {
	const apiUrl = getApiBaseUrl();
	const response = await authenticatedFetch(`${apiUrl}/me/homework/${homeworkId}/submission`);

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

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

/**
 * Sauvegarde un brouillon de rendu.
 */
export async function saveDraftSubmission(
	homeworkId: string,
	responseHtml: string | null
): Promise<HomeworkSubmission> {
	const apiUrl = getApiBaseUrl();
	const response = await authenticatedFetch(`${apiUrl}/me/homework/${homeworkId}/submission`, {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify({ responseHtml })
	});

	if (!response.ok) {
		const errorData = await response.json().catch(() => null);
		throw new Error(errorData?.detail ?? `Erreur lors de la sauvegarde (${response.status})`);
	}

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

/**
 * Soumet définitivement le rendu.
 */
export async function submitHomework(homeworkId: string): Promise<HomeworkSubmission> {
	const apiUrl = getApiBaseUrl();
	const response = await authenticatedFetch(`${apiUrl}/me/homework/${homeworkId}/submission/submit`, {
		method: 'POST'
	});

	if (!response.ok) {
		const errorData = await response.json().catch(() => null);
		throw new Error(errorData?.detail ?? `Erreur lors de la soumission (${response.status})`);
	}

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

/**
 * Upload une pièce jointe au rendu de l'élève.
 */
export async function uploadSubmissionAttachment(
	homeworkId: string,
	file: File
): Promise<HomeworkAttachment> {
	const apiUrl = getApiBaseUrl();
	const formData = new FormData();
	formData.append('file', file);

	const response = await authenticatedFetch(
		`${apiUrl}/me/homework/${homeworkId}/submission/attachments`,
		{
			method: 'POST',
			body: formData
		}
	);

	if (!response.ok) {
		const errorData = await response.json().catch(() => null);
		throw new Error(errorData?.detail ?? "Erreur lors de l'envoi du fichier.");
	}

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