/**
 * Pure helpers for project-note attachments (KAR-344 Phase 3).
 *
 * Storage layout: objects live in the private `project-notes` bucket under
 * `<note_id>/<uuid>-<filename>`. The first path segment is the note id, which
 * the storage RLS policies use to scope access to the note's project owner.
 */

export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024 // 10 MB

export const ALLOWED_ATTACHMENT_MIME = [
  'image/png',
  'image/jpeg',
  'image/webp',
  'image/heic',
] as const

export type AttachmentValidation = { ok: true } | { ok: false; error: string }

export function validateAttachment(file: { size: number; type: string }): AttachmentValidation {
  if (!ALLOWED_ATTACHMENT_MIME.includes(file.type as (typeof ALLOWED_ATTACHMENT_MIME)[number])) {
    return { ok: false, error: 'Nur Bilder (PNG, JPEG, WebP, HEIC) erlaubt.' }
  }
  if (file.size > MAX_ATTACHMENT_BYTES) {
    return { ok: false, error: 'Datei zu groß (max. 10 MB).' }
  }
  return { ok: true }
}

/** Strip directories, lowercase, replace unsafe chars; never empty. */
export function sanitizeFilename(name: string): string {
  const base = name.split(/[/\\]/).pop() ?? ''
  const cleaned = base.toLowerCase().replace(/[^a-z0-9.]+/g, '-')
  if (!cleaned || /^[-.]*$/.test(cleaned)) return 'datei'
  return cleaned
}

/** Build the storage object key: `<note_id>/<uuid>-<sanitized filename>`. */
export function buildStorageKey(noteId: string, uuid: string, filename: string): string {
  return `${noteId}/${uuid}-${sanitizeFilename(filename)}`
}
