import type { Request, Response } from "express";
import { z } from "zod";
import { prisma } from "../../config/prisma.js";
import { ApiError, asyncHandler } from "../../utils/asyncHandler.js";
import { audit } from "../../utils/audit.js";

export const listSettings = asyncHandler(async (_req: Request, res: Response) => {
  const settings = await prisma.setting.findMany({ orderBy: { key: "asc" } });
  res.json({ success: true, data: settings });
});

export const updateSettings = asyncHandler(async (req: Request, res: Response) => {
  const entries: Record<string, string> = req.body;
  if (!entries || typeof entries !== "object") throw new ApiError(400, "بيانات غير صالحة");

  for (const [key, value] of Object.entries(entries)) {
    const existing = await prisma.setting.findUnique({ where: { key } });
    if (existing) {
      await prisma.setting.update({ where: { key }, data: { value: String(value ?? "") } });
    } else {
      await prisma.setting.create({ data: { key, value: String(value ?? "") } });
    }
  }
  await audit(req, "update", "settings", "all", null, entries);
  const settings = await prisma.setting.findMany({ orderBy: { key: "asc" } });
  res.json({ success: true, data: settings });
});

// Document types management
export const createDocumentType = asyncHandler(async (req: Request, res: Response) => {
  const schema = z.object({
    code: z.string().min(1),
    nameAr: z.string().min(1),
    nameEn: z.string().optional().default(""),
    defaultAlertDays: z.number().int().positive().default(30),
    isActive: z.boolean().default(true),
  });
  const data = schema.parse(req.body);
  const exists = await prisma.documentType.findUnique({ where: { code: data.code } });
  if (exists) throw new ApiError(409, "الكود مستخدم بالفعل");
  const type = await prisma.documentType.create({ data });
  await audit(req, "create", "document_type", type.id, null, data);
  res.status(201).json({ success: true, data: type });
});

export const updateDocumentType = asyncHandler(async (req: Request, res: Response) => {
  const id = Number(req.params.id);
  const existing = await prisma.documentType.findUnique({ where: { id } });
  if (!existing) throw new ApiError(404, "النوع غير موجود");
  const schema = z.object({
    code: z.string().min(1).optional(),
    nameAr: z.string().min(1).optional(),
    nameEn: z.string().optional(),
    defaultAlertDays: z.number().int().positive().optional(),
    isActive: z.boolean().optional(),
  });
  const data = schema.parse(req.body);
  const type = await prisma.documentType.update({ where: { id }, data });
  await audit(req, "update", "document_type", id, existing, type);
  res.json({ success: true, data: type });
});

export const deleteDocumentType = asyncHandler(async (req: Request, res: Response) => {
  const id = Number(req.params.id);
  const count = await prisma.document.count({ where: { documentTypeId: id } });
  if (count > 0) throw new ApiError(400, "لا يمكن حذف النوع لوجود مستندات مرتبطة به");
  await prisma.documentType.delete({ where: { id } });
  await audit(req, "delete", "document_type", id);
  res.json({ success: true });
});
