import { describe, expect, it } from 'vitest'

import {
    countImportSourceLines,
    validateImportSource,
} from '@/lib/postImportSourceValidation'

describe ('post import source validation', () => {
  it ('counts trimmed non-empty CRLF and LF rows', () => {
    expect (countImportSourceLines (' one \r\n\r\n two\n')).toBe (2)
  })

  it ('reports invalid protocols and malformed URLs with original line numbers', () => {
    const issues = validateImportSource (
        '\nftp://example.com/file\nhttps://exa mple.com/path')

    expect (issues).toEqual ([
      {
	sourceRow: 2,
	message: 'HTTP または HTTPS の URL ではありません．',
	url: 'ftp://example.com/file' },
      {
	sourceRow: 3,
	message: 'URL の形式が不正です．',
	url: 'https://exa mple.com/path' }])
  })

  it ('detects duplicates after frontend URL normalisation', () => {
    const issues = validateImportSource (
        'https://EXAMPLE.com/path/\nhttps://example.com/path')

    expect (issues).toEqual ([{
      sourceRow: 2,
      message: '1 行目と同じ URL です．',
      url: 'https://example.com/path' }])
  })

  it ('rejects oversized URLs and rows beyond the maximum count', () => {
    const oversized = `https://example.com/${ 'a'.repeat (20 * 1024) }`
    const tooMany = Array.from (
        { length: 101 },
        (_, index) => `https://example.com/${ index }`).join ('\n')

    expect (validateImportSource (oversized)[0]).toMatchObject ({
      sourceRow: 1,
      message: 'URL が長すぎます．' })
    expect (validateImportSource (tooMany).at (-1)).toEqual ({
      sourceRow: 101,
      message: '取込件数は 100 件までです．',
      url: 'https://example.com/100' })
  })
})
