import { z } from 'zod';

/** Setting key holding the per-port Documenso API base URL override. */
export const DOCUMENSO_API_URL_SETTING_KEY = 'documenso_api_url_override';

/**
 * Normalize an admin-supplied Documenso API base URL.
 *
 * `documensoFetch` builds request URLs as `${baseUrl}/api/vN/...`, so the
 * stored value must be a BARE host (no `/api/v1` or `/api/v2` suffix, no
 * trailing slash). An admin pasting `https://sign.example.com/api/v1` would
 * otherwise produce `https://sign.example.com/api/v1/api/v2/envelope/create`
 * → 404 on every send/download, surfaced only as a generic
 * DOCUMENSO_UPSTREAM_ERROR. Strip a trailing `/api/v1`|`/api/v2` and any
 * trailing slashes so the value matches the `DOCUMENSO_API_URL` env-var
 * contract (bare host only). Returns the input unchanged when it is not a
 * non-empty string.
 */
export function normalizeDocumensoApiUrl(value: unknown): unknown {
  if (typeof value !== 'string') return value;
  const trimmed = value.trim();
  if (trimmed.length === 0) return trimmed;
  // Strip a trailing `/api/v1` or `/api/v2` (with optional trailing slash),
  // then strip any remaining trailing slashes.
  return trimmed.replace(/\/api\/v[12]\/?$/i, '').replace(/\/+$/, '');
}

export const upsertSettingSchema = z
  .object({
    key: z.string().min(1).max(100),
    value: z.unknown(),
  })
  .transform((input) => {
    // Normalize + validate the Documenso API URL override on write. Other
    // keys pass through untouched (value: z.unknown()).
    if (input.key === DOCUMENSO_API_URL_SETTING_KEY && typeof input.value === 'string') {
      return { ...input, value: normalizeDocumensoApiUrl(input.value) };
    }
    return input;
  })
  .superRefine((input, ctx) => {
    if (
      input.key === DOCUMENSO_API_URL_SETTING_KEY &&
      typeof input.value === 'string' &&
      input.value.length > 0
    ) {
      const result = z.string().url().safeParse(input.value);
      if (!result.success) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ['value'],
          message: 'Documenso API URL must be a valid URL with no /api/v1 or /api/v2 suffix',
        });
      }
    }
  });

export type UpsertSettingInput = z.infer<typeof upsertSettingSchema>;

export const deleteSettingSchema = z.object({
  key: z.string().min(1).max(100),
});

export type DeleteSettingInput = z.infer<typeof deleteSettingSchema>;
