import type { APIRoute } from 'astro'
import { getDb } from '../../../lib/db'
import {
  validateBearer, unauthorizedResponse, badRequestResponse,
  jsonResponse, notFoundResponse, hasForbiddenFields,
} from '../../../lib/auth'

export const GET: APIRoute = ({ params }) => {
  const db = getDb()
  const article = db.prepare('SELECT * FROM articles WHERE slug = ?').get(params.slug)
  if (!article) return notFoundResponse()
  return jsonResponse(article)
}

export const PUT: APIRoute = async ({ params, request }) => {
  if (!validateBearer(request)) return unauthorizedResponse()

  let body: Record<string, unknown>
  try { body = await request.json() } catch { return badRequestResponse('Invalid JSON') }

  if (hasForbiddenFields(body)) return badRequestResponse('Forbidden field')

  const db = getDb()
  const existing = db.prepare('SELECT id FROM articles WHERE slug = ?').get(params.slug)
  if (!existing) return notFoundResponse()

  const allowed = ['title', 'content_sv', 'category', 'featured', 'published', 'published_at', 'meta_title', 'meta_desc']
  const updates: string[] = []
  const values: unknown[] = []

  for (const key of allowed) {
    if (key in body) {
      updates.push(`${key} = ?`)
      values.push(body[key])
    }
  }

  if (updates.length === 0) return badRequestResponse('No valid fields to update')

  updates.push("last_updated = datetime('now')")
  values.push(params.slug)

  db.prepare(`UPDATE articles SET ${updates.join(', ')} WHERE slug = ?`).run(...values)
  return jsonResponse({ success: true })
}

export const DELETE: APIRoute = async ({ params, request }) => {
  if (!validateBearer(request)) return unauthorizedResponse()

  const db = getDb()
  const existing = db.prepare('SELECT id FROM articles WHERE slug = ?').get(params.slug)
  if (!existing) return notFoundResponse()

  db.prepare("UPDATE articles SET published = 0, last_updated = datetime('now') WHERE slug = ?").run(params.slug)
  return jsonResponse({ success: true, message: 'Article unpublished (not deleted)' })
}
