import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import fs from 'fs';
import { importResidentsFromExcel } from '#services/residentExcelService';
import { Req, Res } from '#interfaces/IApi';
import verify, { requireAdmin } from '#middlewares/auth';
import { upload } from '#services/file-system/uploadService';
import { Errors } from '#interfaces/error/ISpecificErrors';
import { sendSuccess } from '#utils/responseUtils';

export default (_express: Application) => {
	return <Resource>{
		post: {
			middleware: [verify, requireAdmin, upload],
			handler: async (req: Req, res: Res) => {
				try {
					const file = req.file as Express.Multer.File | undefined;
					if (!file) {
						return res.error(
							Errors.validation([
								{
									field: 'file',
									code: 'MISSING_FILE',
									message: { vi: 'Không có file được upload', en: 'No file uploaded' },
								},
							]),
						);
					}

					// Delegate full import processing to service
					const raw = await importResidentsFromExcel(file.path, { userId: req.user?.id || null });

					// Cleanup uploaded file
					fs.unlink(file.path, () => {});

					// Support both legacy array return and new { results } shape (no summary)
					const results = Array.isArray(raw) ? raw : raw?.results || [];

					const succeeded = results.filter((r) => (r as any).success).map((r: any) => (r as any).resident);
					const failed = results.filter((r) => !(r as any).success);

					if (failed.length === 0) return sendSuccess(res, { successful: succeeded });
					if (succeeded.length === 0)
						return res
							.status(422)
							.json({ success: false, errors: failed.map((f: any) => ({ row: f.row, error: f.error })) });

					return res.status(207).json({
						success: true,
						data: { successful: succeeded, failed: failed.map((f: any) => ({ row: f.row, error: f.error })) },
					});
				} catch (error) {
					// Ensure temp file removed if service threw
					try {
						const filePath = (req.file as Express.Multer.File | undefined)?.path;
						if (filePath) fs.unlink(filePath, () => {});
					} catch {
						// Ignore cleanup errors
					}
					return res.error(error);
				}
			},
		},
	};
};
