import express from 'express'
import cors from 'cors'
import {
    ensureDataFiles,
    readAllYearsData,
    readYearData,
    readStatus
} from './lib/cache.js'

const app = express()
app.use(cors())
app.use(express.json())

ensureDataFiles()

let memoryCache = {
    updatedAt: null,
    name: '七十二家房客',
    coverUrl: '',
    displayType: 0,
    years: [],
    items: []
}

function toSimpleItem(item) {
    return {
        id: item.id,
        title: item.title,
        coverUrl: item.coverUrl,
        releasedAt: item.releasedAt,
        timeLength: item.timeLength,
        videoUrl: item.videoUrl
    }
}

function refreshMemoryCache() {
    const cache = readAllYearsData()
    memoryCache = {
        updatedAt: cache.updatedAt,
        name: cache.name || '七十二家房客',
        coverUrl: cache.coverUrl || '',
        displayType: cache.displayType || 0,
        years: cache.years || [],
        items: (cache.items || []).map(toSimpleItem)
    }

    console.log(
        '[server] 内存缓存已刷新:',
        'total=', memoryCache.items.length,
        'years=', memoryCache.years.length
    )
}

refreshMemoryCache()

app.get('/api/qishier/all', (_req, res) => {
    res.json({
        updatedAt: memoryCache.updatedAt,
        name: memoryCache.name,
        coverUrl: memoryCache.coverUrl,
        displayType: memoryCache.displayType,
        total: memoryCache.items.length,
        years: memoryCache.years,
        list: memoryCache.items
    })
})

app.get('/api/qishier/list', (req, res) => {
    const page = Math.max(1, Number(req.query.page || 1))
    const pageSize = Math.max(1, Math.min(100, Number(req.query.pageSize || 50)))

    const total = memoryCache.items.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = memoryCache.items.slice(start, end)

    res.json({
        updatedAt: memoryCache.updatedAt,
        name: memoryCache.name,
        coverUrl: memoryCache.coverUrl,
        displayType: memoryCache.displayType,
        total,
        page,
        pageSize,
        hasMore: end < total,
        years: memoryCache.years,
        list
    })
})

app.get('/api/qishier/year/:year', (req, res) => {
    try {
        const year = Number(req.params.year)
        const data = readYearData(year)

        res.json({
            updatedAt: data.updatedAt,
            name: '七十二家房客',
            coverUrl: '',
            displayType: 0,
            total: data.items?.length || 0,
            years: [year],
            list: (data.items || []).map(toSimpleItem)
        })
    } catch (error) {
        res.status(500).json({
            message: '读取年度缓存失败',
            error: error.message
        })
    }
})

app.post('/api/qishier/refresh', (_req, res) => {
    try {
        refreshMemoryCache()
        res.json({
            message: '缓存已刷新',
            total: memoryCache.items.length,
            updatedAt: memoryCache.updatedAt
        })
    } catch (error) {
        res.status(500).json({
            message: '刷新缓存失败',
            error: error.message
        })
    }
})

app.get('/api/qishier/status', (_req, res) => {
    try {
        const status = readStatus()
        res.json(status)
    } catch (error) {
        res.status(500).json({
            message: '读取状态失败',
            error: error.message
        })
    }
})

app.listen(23822, () => {
    console.log('Node 服务已启动: http://127.0.0.1:23822')
})
