import { ENV_CONFIG } from '@/lib/env-config';
import { API_KEY } from '@/lib/config';

// Mocks e helpers para API de Atribuições (assignments)
export type MockAssignment = {
	id: string;
	title: string;
	description?: string;
	assigned_to?: string;
	status?: string;
	due_date?: string; // ISO date
	created_at?: string;
	updated_at?: string;
};

let ASSIGNMENTS: MockAssignment[] = [
	{
		id: 'm-1',
		title: 'Revisar relatórios mensais',
		description: 'Conferir os relatórios e enviar feedback',
		assigned_to: 'med1',
		status: 'open',
		due_date: '2025-10-20',
		created_at: new Date().toISOString(),
		updated_at: new Date().toISOString(),
	},
	{
		id: 'm-2',
		title: 'Preparar apresentação',
		description: 'Slides para reunião de equipe',
		assigned_to: 'med2',
		status: 'in_progress',
		due_date: '2025-10-25',
		created_at: new Date().toISOString(),
		updated_at: new Date().toISOString(),
	},
	{
		// Inserção do objeto de atribuição fornecido pelo usuário
		id: '12345678-1234-1234-1234-123456789012',
		patient_id: '12345678-1234-1234-1234-123456789012',
		user_id: '12345678-1234-1234-1234-123456789012',
		role: 'medico',
		created_at: '2024-01-15T10:30:00Z',
		created_by: '12345678-1234-1234-1234-123456789012',
		title: 'Atribuição paciente',
		description: 'Atribuição criada a partir do payload de exemplo',
		assigned_to: '12345678-1234-1234-1234-123456789012',
		status: 'assigned',
		updated_at: '2024-01-15T10:30:00Z',
	} as unknown as MockAssignment,
];

export async function listAssignments(): Promise<MockAssignment[]> {
	await new Promise((r) => setTimeout(r, 80));
	return ASSIGNMENTS.slice();
}

export async function getAssignment(id: string): Promise<MockAssignment | null> {
	await new Promise((r) => setTimeout(r, 60));
	return ASSIGNMENTS.find((a) => a.id === id) ?? null;
}

export async function createAssignment(input: Omit<MockAssignment, 'id' | 'created_at' | 'updated_at'>): Promise<MockAssignment> {
	const newItem: MockAssignment = {
		id: `m-${Date.now()}`,
		...input,
		created_at: new Date().toISOString(),
		updated_at: new Date().toISOString(),
	} as MockAssignment;
	ASSIGNMENTS.push(newItem);
	await new Promise((r) => setTimeout(r, 100));
	return newItem;
}

export async function updateAssignment(id: string, partial: Partial<MockAssignment>): Promise<MockAssignment | null> {
	const idx = ASSIGNMENTS.findIndex((a) => a.id === id);
	if (idx === -1) return null;
	ASSIGNMENTS[idx] = { ...ASSIGNMENTS[idx], ...partial, updated_at: new Date().toISOString() };
	await new Promise((r) => setTimeout(r, 60));
	return ASSIGNMENTS[idx];
}

export async function deleteAssignment(id: string): Promise<boolean> {
	const prev = ASSIGNMENTS.length;
	ASSIGNMENTS = ASSIGNMENTS.filter((a) => a.id !== id);
	await new Promise((r) => setTimeout(r, 40));
	return ASSIGNMENTS.length < prev;
}

// Helper: cria uma atribuição paciente-usuário em endpoint externo (mock)
export async function createPatientAssignmentRemote({ patient_id, user_id, role }: { patient_id: string; user_id: string; role: string }, token?: string) {
	const url = 'https://mock.apidog.com/m1/1053378-0-default/rest/v1/patient_assignments';
	const headers: Record<string,string> = {
		apikey: API_KEY || '',
		'Content-Type': 'application/json',
	};
	if (token) headers['Authorization'] = `Bearer ${token}`;

	const body = JSON.stringify({ patient_id, user_id, role });

	const res = await fetch(url, { method: 'POST', headers, body, redirect: 'follow' as RequestRedirect });
	let text: string;
	try {
		const json = await res.json();
		return json;
	} catch (err) {
		text = await res.text();
		return text;
	}
}
