import type { CustomFieldType } from "@prisma/client";
import { HttpError } from "../middleware/errorHandler";

// Shared by the card custom-field-value setter (validates what a user submits)
// and card creation (coerces a field's stored defaultValue into the same shape).
export function coerceCustomFieldValue(
  type: CustomFieldType,
  raw: unknown,
  options?: { label: string; color: string }[] | null
): unknown {
  if (raw === null || raw === undefined || raw === "") return null;

  switch (type) {
    case "NUMBER":
    case "RATING": {
      const n = typeof raw === "number" ? raw : Number(raw);
      if (Number.isNaN(n)) throw new HttpError(400, `Value for a ${type} field must be a number`);
      return n;
    }
    case "CHECKBOX": {
      if (typeof raw === "boolean") return raw;
      if (raw === "true" || raw === "false") return raw === "true";
      throw new HttpError(400, "Value for a CHECKBOX field must be a boolean");
    }
    case "DATE": {
      const d = new Date(raw as string);
      if (Number.isNaN(d.getTime())) throw new HttpError(400, "Value for a DATE field must be a valid date");
      return raw as string;
    }
    case "DROPDOWN":
    case "STATUS": {
      const str = String(raw);
      if (options && options.length > 0 && !options.some((o) => o.label === str)) {
        throw new HttpError(400, `"${str}" is not one of this field's options`);
      }
      return str;
    }
    case "FILE": {
      // Stored as an array of previously-uploaded files — [{id, url, filename,
      // mimeType, sizeBytes}, ...] — never typed directly by a user, only ever
      // produced by the upload endpoint (or the migration tool writing directly
      // to the same shape), so we just validate the shape rather than coerce it.
      if (!Array.isArray(raw)) throw new HttpError(400, "Value for a FILE field must be a list of uploaded files");
      if (raw.length === 0) return null;
      return raw.map((f) => {
        const file = f as Record<string, unknown>;
        if (typeof file.id !== "string" || typeof file.url !== "string") {
          throw new HttpError(400, "Each FILE field entry needs an id and a url");
        }
        return {
          id: file.id,
          url: file.url,
          filename: typeof file.filename === "string" ? file.filename : null,
          mimeType: typeof file.mimeType === "string" ? file.mimeType : null,
          sizeBytes: typeof file.sizeBytes === "number" ? file.sizeBytes : null,
        };
      });
    }
    case "PHONE": {
      if (typeof raw === "object" && raw !== null && "number" in (raw as Record<string, unknown>)) {
        const obj = raw as Record<string, unknown>;
        const number = typeof obj.number === "string" ? obj.number.trim() : "";
        if (number === "") return null;
        return {
          number,
          countryCode: typeof obj.countryCode === "string" && obj.countryCode ? obj.countryCode : null,
        };
      }
      const number = String(raw).trim();
      return number === "" ? null : { number, countryCode: null };
    }
    case "TEXT":
    case "PERSON":
    case "LINK":
    default:
      return String(raw);
  }
}
