/**
 * Pure Tag domain logic — validation + normalisation for creating/editing a
 * portfolio Tag (ADR-0013). Kept free of DB access so it unit-tests cleanly and
 * is shared by the tag routes. The DB's case-insensitive unique index is the
 * ultimate guard against duplicate names; this gives a friendly pre-check.
 */

export const MAX_TAG_NAME_LENGTH = 30;

/** A hex colour: #rgb or #rrggbb (case-insensitive). */
const HEX_COLOUR = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;

export interface TagDraft {
  name: string;
  colour: string;
}

export type TagValidation =
  | { ok: true; tag: TagDraft }
  | { ok: false; error: string };

export function validateTagDraft(
  input: TagDraft,
  existingNames: string[],
): TagValidation {
  const name = input.name.trim();
  if (name.length === 0) return { ok: false, error: "Tag name is required" };
  if (name.length > MAX_TAG_NAME_LENGTH) {
    return {
      ok: false,
      error: `Tag name must be ${MAX_TAG_NAME_LENGTH} characters or fewer`,
    };
  }
  const lower = name.toLowerCase();
  if (existingNames.some((existing) => existing.trim().toLowerCase() === lower)) {
    return { ok: false, error: "A tag with this name already exists" };
  }
  const colour = input.colour.trim().toLowerCase();
  if (!HEX_COLOUR.test(colour)) {
    return { ok: false, error: "Colour must be a hex code like #7c3aed" };
  }
  return { ok: true, tag: { name, colour } };
}
