export const dynamic = 'force-dynamic'
import { NextResponse } from 'next/server'
import * as fs from 'fs'

const DATA_DIR = fs.existsSync('/data') ? '/data' : '/tmp'
const COUNTDOWNS_PATH = `${DATA_DIR}/tablet-countdowns.json`

export interface Countdown {
  id: string
  label: string
  date: string // YYYY-MM-DD
  emoji?: string
  color?: string // hex or data-* token name (e.g. "data-rose")
  note?: string
  createdAt: string
  updatedAt: string
}

const DEFAULT_COUNTDOWNS: Countdown[] = [
  {
    id: 'tokyo',
    label: 'Токио',
    date: '2026-10-15',
    emoji: '🗼',
    color: 'data-rose',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
]

function load(): Countdown[] {
  try {
    if (fs.existsSync(COUNTDOWNS_PATH)) {
      return JSON.parse(fs.readFileSync(COUNTDOWNS_PATH, 'utf-8'))
    }
    // первая загрузка — создать дефолтный файл
    save(DEFAULT_COUNTDOWNS)
    return DEFAULT_COUNTDOWNS
  } catch {
    return []
  }
}

function save(list: Countdown[]) {
  try {
    fs.writeFileSync(COUNTDOWNS_PATH, JSON.stringify(list, null, 2))
  } catch {}
}

export async function GET() {
  const all = load()
  // сортируем по дате возрастания
  const sorted = [...all].sort((a, b) => a.date.localeCompare(b.date))
  return NextResponse.json({ countdowns: sorted })
}

export async function POST(req: Request) {
  const body = await req.json()
  if (!body.label || !body.date) {
    return NextResponse.json({ error: 'label_and_date_required' }, { status: 400 })
  }
  const list = load()
  const cd: Countdown = {
    id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
    label: String(body.label).slice(0, 60),
    date: String(body.date).slice(0, 10),
    emoji: body.emoji?.slice(0, 4) || undefined,
    color: body.color || undefined,
    note: body.note?.slice(0, 200) || undefined,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  }
  list.push(cd)
  save(list)
  return NextResponse.json({ countdown: cd })
}

export async function PUT(req: Request) {
  const body = await req.json()
  const { id, ...updates } = body
  if (!id) return NextResponse.json({ error: 'id_required' }, { status: 400 })
  const list = load()
  const idx = list.findIndex(c => c.id === id)
  if (idx < 0) return NextResponse.json({ error: 'not_found' }, { status: 404 })
  list[idx] = { ...list[idx], ...updates, id, updatedAt: new Date().toISOString() }
  save(list)
  return NextResponse.json({ countdown: list[idx] })
}

export async function DELETE(req: Request) {
  const url = new URL(req.url)
  const id = url.searchParams.get('id')
  if (!id) return NextResponse.json({ error: 'id_required' }, { status: 400 })
  const list = load().filter(c => c.id !== id)
  save(list)
  return NextResponse.json({ ok: true })
}
