import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { ResidentDocumentProvider } from '#providers/ResidentDocumentProvider';
import { Req, Res } from '#interfaces/IApi';
import verify, { attachPermissions } from '#middlewares/auth';
import { validateZod } from '#middlewares/validators';
import { z } from 'zod';
import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';
import { Errors } from '#interfaces/error';
import { sendSuccess } from '#utils/responseUtils';

extendZodWithOpenApi(z);

const DocumentTypeEnum = z.enum([
  'id_card',
  'cccd_front',
  'cccd_back',
  'portrait',
  'passport',
  'household_registration',
  'temporary_residence',
  'contract',
  'other',
]);

const ResidentDocumentCreateBodySchema = z
  .object({
    file_id: z.string().uuid().describe('ID of the uploaded file from /api/v1/files'),
    document_type: DocumentTypeEnum.openapi({ example: 'portrait' }),
    document_name: z.string().max(255).optional().openapi({ example: 'ảnh chân dung' }),
    description: z.string().optional().openapi({ example: 'string' }),
    is_primary: z.boolean().optional().default(false).openapi({ example: false }),
  })
  .openapi('ResidentDocumentCreateBody');

export const ResidentDocumentBatchCreateBodySchema = z
  .array(ResidentDocumentCreateBodySchema)
  .min(1, 'At least one document is required')
  .openapi('ResidentDocumentBatchCreateBodyByToken');

export default (_express: Application) => {
  const documentProvider = ResidentDocumentProvider.getInstance();

  return <Resource>{
    post: {
      middleware: [verify, attachPermissions, validateZod(ResidentDocumentBatchCreateBodySchema)],
      handler: async (req: Req, res: Res) => {
        try {
          const residentId = (req.user as any)?.resident_id ?? null;
          if (!residentId) {
            return res.error(
              Errors.validation([
                {
                  field: 'resident_id',
                  code: 'MISSING_RESIDENT',
                  message: { vi: 'Không tìm thấy resident_id trong token', en: 'resident_id missing in token' },
                },
              ]),
            );
          }

          const validated = req.body as z.infer<typeof ResidentDocumentBatchCreateBodySchema>;

          const createdDocuments = await Promise.all(
            validated.map((doc) =>
              documentProvider.create({
                file_id: doc.file_id,
                document_type: doc.document_type,
                document_name: doc.document_name || null,
                description: doc.description || null,
                is_primary: doc.is_primary ?? false,
                status: req.user?.permissions?.includes('document:create') ? 'approved' : 'pending',
                resident_id: residentId,
                created_by: req.user?.id || null,
              } as any),
            ),
          );

          return sendSuccess(res, createdDocuments);
        } catch (error) {
          return res.error(error);
        }
      },
    },
  };
};
