import { promises as fs } from 'fs'
import path from 'path'
import { getCurrentSeasonSlug } from '../../utils/spielplan-data.js'

const SEASON_FILE_PATTERN = /^mannschaften_(\d{2}--\d{2})\.csv$/

async function collectSeasonFiles(dirPath) {
  try {
    const files = await fs.readdir(dirPath)
    return files
      .map((name) => {
        const match = name.match(SEASON_FILE_PATTERN)
        return match ? match[1] : null
      })
      .filter(Boolean)
  } catch (error) {
    if (error?.code === 'ENOENT') return []
    throw error
  }
}

export default defineEventHandler(async () => {
  try {
    const cwd = process.cwd()
    const dirs = [
      path.join(cwd, 'server/data/public-data'),
      path.join(cwd, '../server/data/public-data'),
      path.join(cwd, '.output/public/data'),
      path.join(cwd, 'public/data')
    ]

    const seasonLists = await Promise.all(dirs.map((dir) => collectSeasonFiles(dir)))
    const allSeasons = [...new Set(seasonLists.flat())].sort().reverse()

    const currentSeason = getCurrentSeasonSlug()
    const seasons = allSeasons.includes(currentSeason)
      ? allSeasons
      : [currentSeason, ...allSeasons]

    return {
      success: true,
      seasons,
      currentSeason,
      defaultSeason: seasons[0] || currentSeason
    }
  } catch (error) {
    console.error('Fehler beim Laden der Mannschafts-Saisons:', error)
    return {
      success: false,
      seasons: [getCurrentSeasonSlug()],
      currentSeason: getCurrentSeasonSlug(),
      defaultSeason: getCurrentSeasonSlug()
    }
  }
})
