import prisma from "../prisma/client.js";

// get doctors

export const getAllDoctors = async (req, res) => {
	try {
		const doctors = await prisma.doctor.findMany({
			include: {
				departments: {
					include: {
						department: true,
						timing: true,
					},
				},
			},
			orderBy: {name: "asc"},
		});

		const formatted = doctors.map((doc, index) => ({
			SL_NO: String(index + 1),
			doctorId: doc.doctorId,
			name: doc.name,
			designation: doc.designation,
			workingStatus: doc.workingStatus,
			qualification: doc.qualification,

			departments: doc.departments.map((d) => {
				const t = d.timing || {};

				const timingArray = [
					t.monday && `Monday ${t.monday}`,
					t.tuesday && `Tuesday ${t.tuesday}`,
					t.wednesday && `Wednesday ${t.wednesday}`,
					t.thursday && `Thursday ${t.thursday}`,
					t.friday && `Friday ${t.friday}`,
					t.saturday && `Saturday ${t.saturday}`,
					t.sunday && `Sunday ${t.sunday}`,
					t.additional && t.additional,
				].filter(Boolean);

				return {
					departmentId: d.department.departmentId,
					departmentName: d.department.name,
					timing: timingArray.join(" & "),
				};
			}),
		}));

		res.status(200).json({
			success: true,
			data: formatted,
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to fetch doctors",
		});
	}
};

// get doctor by id

export const getDoctorByDoctorId = async (req, res) => {
	try {
		const {doctorId} = req.params;

		const doctor = await prisma.doctor.findUnique({
			where: {doctorId},
			include: {
				departments: {
					include: {
						department: true,
						timing: true,
					},
				},
			},
		});

		if (!doctor) {
			return res.status(404).json({
				success: false,
				message: "Doctor not found",
			});
		}

		const response = {
			doctorId: doctor.doctorId,
			name: doctor.name,
			designation: doctor.designation,
			workingStatus: doctor.workingStatus,
			qualification: doctor.qualification,
			departments: doctor.departments.map((d) => ({
				departmentId: d.department.departmentId,
				departmentName: d.department.name,
				timing: d.timing || {},
			})),
		};

		res.status(200).json({
			success: true,
			data: response,
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to fetch doctor",
		});
	}
};

// get doctors by department
export const getDoctorsByDepartmentId = async (req, res) => {
	try {
		const {Department_ID} = req.query;

		if (!Department_ID) {
			return res.status(400).json({
				success: false,
				message: "Department_ID is required",
			});
		}

		const department = await prisma.department.findUnique({
			where: {departmentId: Department_ID},
		});

		if (!department) {
			return res.status(404).json({
				success: false,
				message: "Department not found",
			});
		}

		const doctors = await prisma.doctorDepartment.findMany({
			where: {departmentId: department.id},
			include: {
				doctor: true,
			},
		});

		const result = doctors.map((d) => ({
			GG_ID: d.doctor.doctorId,
			Name: d.doctor.name,
		}));

		res.status(200).json({
			success: true,
			data: result,
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to fetch doctors",
		});
	}
};

// add doctors
export const createDoctor = async (req, res) => {
	try {
		const {
			doctorId,
			name,
			designation,
			workingStatus,
			qualification,
			departments,
		} = req.body;

		const doctor = await prisma.doctor.create({
			data: {
				doctorId,
				name,
				designation,
				workingStatus,
				qualification,
			},
		});

		for (const dep of departments) {
			const department = await prisma.department.findUnique({
				where: {departmentId: dep.departmentId},
			});

			if (!department) continue;

			const doctorDepartment = await prisma.doctorDepartment.create({
				data: {
					doctorId: doctor.id,
					departmentId: department.id,
				},
			});

			if (dep.timing) {
				await prisma.doctorTiming.create({
					data: {
						doctorDepartmentId: doctorDepartment.id,
						...dep.timing,
					},
				});
			}
		}

		res.status(201).json({
			success: true,
			message: "Doctor created successfully",
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to create doctor",
		});
	}
};

//update doctors
export const updateDoctor = async (req, res) => {
	try {
		const {doctorId} = req.params;
		const {name, designation, workingStatus, qualification, departments} =
			req.body;

		const doctor = await prisma.doctor.findUnique({
			where: {doctorId},
		});

		if (!doctor) {
			return res
				.status(404)
				.json({success: false, message: "Doctor not found"});
		}

		await prisma.doctor.update({
			where: {id: doctor.id},
			data: {name, designation, workingStatus, qualification},
		});

		const oldRelations = await prisma.doctorDepartment.findMany({
			where: {doctorId: doctor.id},
		});

		for (const rel of oldRelations) {
			await prisma.doctorTiming.deleteMany({
				where: {doctorDepartmentId: rel.id},
			});
		}

		await prisma.doctorDepartment.deleteMany({
			where: {doctorId: doctor.id},
		});

		for (const dep of departments) {
			const department = await prisma.department.findUnique({
				where: {departmentId: dep.departmentId},
			});

			if (!department) continue;

			const doctorDepartment = await prisma.doctorDepartment.create({
				data: {
					doctorId: doctor.id,
					departmentId: department.id,
				},
			});

			if (dep.timing) {
				const {id, doctorDepartmentId, createdAt, updatedAt, ...cleanTiming} =
					dep.timing;

				await prisma.doctorTiming.create({
					data: {
						doctorDepartmentId: doctorDepartment.id,
						...cleanTiming,
					},
				});
			}
		}

		res
			.status(200)
			.json({success: true, message: "Doctor updated successfully"});
	} catch (error) {
		console.error("Update Error:", error);
		res.status(500).json({success: false, message: "Failed to update doctor"});
	}
};
//delete doctor

export const deleteDoctor = async (req, res) => {
	try {
		const {doctorId} = req.params;

		const doctor = await prisma.doctor.findUnique({
			where: {doctorId},
		});

		if (!doctor) {
			return res.status(404).json({
				success: false,
				message: "Doctor not found",
			});
		}

		const doctorDepartments = await prisma.doctorDepartment.findMany({
			where: {doctorId: doctor.id},
		});

		for (const dd of doctorDepartments) {
			await prisma.doctorTiming.deleteMany({
				where: {doctorDepartmentId: dd.id},
			});
		}

		await prisma.doctorDepartment.deleteMany({
			where: {doctorId: doctor.id},
		});

		await prisma.doctor.delete({
			where: {id: doctor.id},
		});

		res.status(200).json({
			success: true,
			message: "Doctor deleted successfully",
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to delete doctor",
		});
	}
};

// get doctor timings

export const getDoctorTimings = async (req, res) => {
	try {
		const doctors = await prisma.doctor.findMany({
			include: {
				departments: {
					include: {
						timing: true,
					},
				},
			},
		});

		const result = doctors.map((doc) => {
			const timing = doc.departments[0]?.timing || {};

			return {
				Doctor_ID: doc.doctorId,
				Doctor: doc.name,
				Monday: timing.monday || "",
				Tuesday: timing.tuesday || "",
				Wednesday: timing.wednesday || "",
				Thursday: timing.thursday || "",
				Friday: timing.friday || "",
				Saturday: timing.saturday || "",
				Sunday: timing.sunday || "",
				Additional: timing.additional || "",
			};
		});

		res.status(200).json({
			success: true,
			data: result,
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to fetch doctor timings",
		});
	}
};
// get doctor timings by id

export const getDoctorTimingById = async (req, res) => {
	try {
		const {doctorId} = req.params;

		const doctor = await prisma.doctor.findUnique({
			where: {doctorId},
			include: {
				departments: {
					include: {
						department: true,
						timing: true,
					},
				},
			},
		});

		if (!doctor) {
			return res.status(404).json({
				success: false,
				message: "Doctor not found",
			});
		}

		const result = {
			doctorId: doctor.doctorId,
			doctorName: doctor.name,
			departments: doctor.departments.map((d) => ({
				departmentId: d.department.departmentId,
				departmentName: d.department.name,
				timing: d.timing || {},
			})),
		};

		res.status(200).json({
			success: true,
			data: result,
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to fetch doctor timing",
		});
	}
};
