import { describe, it, expect } from 'vitest'
import {
  MAX_ATTACHMENT_BYTES,
  ALLOWED_ATTACHMENT_MIME,
  sanitizeFilename,
  buildStorageKey,
  validateAttachment,
} from '../attachments'

describe('validateAttachment', () => {
  it('accepts an allowed image within the size limit', () => {
    expect(validateAttachment({ size: 1024, type: 'image/png' })).toEqual({ ok: true })
  })

  it('rejects a disallowed mime type', () => {
    const res = validateAttachment({ size: 1024, type: 'application/pdf' })
    expect(res.ok).toBe(false)
  })

  it('rejects a file over the size limit', () => {
    const res = validateAttachment({ size: MAX_ATTACHMENT_BYTES + 1, type: 'image/png' })
    expect(res.ok).toBe(false)
  })

  it('accepts every declared allowed mime', () => {
    for (const type of ALLOWED_ATTACHMENT_MIME) {
      expect(validateAttachment({ size: 10, type }).ok).toBe(true)
    }
  })
})

describe('sanitizeFilename', () => {
  it('strips directory components', () => {
    expect(sanitizeFilename('../../etc/passwd.png')).toBe('passwd.png')
    expect(sanitizeFilename('C:\\evil\\foto.jpg')).toBe('foto.jpg')
  })

  it('replaces unsafe characters with a dash and lowercases', () => {
    expect(sanitizeFilename('Wert Strom #3!.PNG')).toBe('wert-strom-3-.png')
  })

  it('falls back to a default when empty after sanitizing', () => {
    expect(sanitizeFilename('')).toBe('datei')
    expect(sanitizeFilename('///')).toBe('datei')
  })
})

describe('buildStorageKey', () => {
  it('namespaces the object under the note id', () => {
    const key = buildStorageKey('note-1', 'abcd', 'Foto.png')
    expect(key).toBe('note-1/abcd-foto.png')
  })

  it('uses the first path segment as the note id (matches storage RLS)', () => {
    const key = buildStorageKey('11111111-1111-4111-8111-111111111111', 'u', 'x.jpg')
    expect(key.split('/')[0]).toBe('11111111-1111-4111-8111-111111111111')
  })
})
