import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/lib/db'
import { seedIfEmpty } from '@/lib/seed'

const PLATFORM_MAP: Record<number, string> = { 1: 'iOS', 2: 'Android', 3: 'HarmonyOS', 4: 'Windows', 5: 'macOS', 6: 'Linux', 7: 'Web' }
const PLATFORM_REVERSE: Record<string, number> = Object.fromEntries(Object.entries(PLATFORM_MAP).map(([k, v]) => [v, Number(k)]))

const FILE_TYPES_BY_PLATFORM: Record<number, string[]> = {
  1: ['ipa'], 2: ['apk', 'aab'], 3: ['hap'], 4: ['exe', 'msi', 'appx'], 5: ['dmg', 'pkg'], 6: ['deb', 'rpm', 'AppImage'], 7: [],
}

const DIST_TYPES_BY_PLATFORM: Record<number, { value: string; label: string }[]> = {
  1: [{ value: 'app_store', label: 'App Store' }, { value: 'testflight', label: 'TestFlight' }, { value: 'enterprise', label: '企业签名' }],
  2: [{ value: 'google_play', label: 'Google Play' }, { value: 'direct', label: '直接下载' }, { value: 'huawei', label: '华为应用市场' }],
  3: [{ value: 'huawei', label: '华为应用市场' }, { value: 'direct', label: '直接下载' }],
  4: [{ value: 'microsoft_store', label: 'Microsoft Store' }, { value: 'direct', label: '直接下载' }],
  5: [{ value: 'app_store', label: 'Mac App Store' }, { value: 'direct', label: '直接下载' }],
  6: [{ value: 'direct', label: '直接下载' }],
  7: [{ value: 'direct', label: '直接访问' }],
}

export async function GET(req: NextRequest) {
  seedIfEmpty()
  const db = getDb()
  const appId = req.nextUrl.searchParams.get('app_id')
  const meta = req.nextUrl.searchParams.get('meta')

  // 返回枚举元数据
  if (meta === 'enums') {
    return NextResponse.json({ platforms: PLATFORM_MAP, fileTypes: FILE_TYPES_BY_PLATFORM, distTypes: DIST_TYPES_BY_PLATFORM })
  }

  if (appId) {
    const app = db.prepare('SELECT * FROM applications WHERE id = ?').get(appId) as Record<string, unknown> | undefined
    if (!app) return NextResponse.json({ error: 'not found' }, { status: 404 })
    const platforms = db.prepare('SELECT * FROM app_platforms WHERE app_id = ? ORDER BY id').all(appId) as Record<string, unknown>[]
    const versions = db.prepare('SELECT * FROM app_platform_versions WHERE app_id = ? ORDER BY major_version DESC, minor_version DESC, patch_version DESC').all(appId) as Record<string, unknown>[]
    const parsedVersions = versions.map(v => ({
      ...v,
      changelog: JSON.parse(v.changelog as string),
      platform_name: PLATFORM_MAP[(platforms.find(p => p.id === v.platform_id) as Record<string, unknown>)?.platform_type as number] || '未知',
    }))
    const parsedPlatforms = platforms.map(p => ({
      ...p,
      platform_name: PLATFORM_MAP[p.platform_type as number] || '未知',
      file_types: FILE_TYPES_BY_PLATFORM[p.platform_type as number] || [],
      dist_types: DIST_TYPES_BY_PLATFORM[p.platform_type as number] || [],
    }))
    return NextResponse.json({ ...app, platforms: parsedPlatforms, versions: parsedVersions })
  }

  const apps = db.prepare('SELECT * FROM applications ORDER BY id DESC').all() as Record<string, unknown>[]
  const result = apps.map(app => {
    const platforms = db.prepare('SELECT * FROM app_platforms WHERE app_id = ?').all(app.id) as Record<string, unknown>[]
    const versionCount = (db.prepare('SELECT COUNT(*) as c FROM app_platform_versions WHERE app_id = ?').get(app.id) as { c: number }).c
    return { ...app, platforms: platforms.map(p => ({ ...p, platform_name: PLATFORM_MAP[p.platform_type as number] || '未知' })), versionCount }
  })
  return NextResponse.json(result)
}

export async function POST(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { action } = body
  const now = new Date().toISOString().replace('T', ' ').substring(0, 19)

  if (action === 'create_app') {
    const { name, package_name, description, logo_url } = body
    const result = db.prepare('INSERT INTO applications (name, package_name, description, logo_url, status, create_time, update_time) VALUES (?, ?, ?, ?, 1, ?, ?)').run(name, package_name || '', description || '', logo_url || '', now, now)
    return NextResponse.json({ id: result.lastInsertRowid })
  }

  if (action === 'add_platform') {
    const { app_id, platform_type, description } = body
    const pt = typeof platform_type === 'string' ? (PLATFORM_REVERSE[platform_type] || 2) : platform_type
    const result = db.prepare('INSERT INTO app_platforms (app_id, platform_type, description, extend_info, create_time) VALUES (?, ?, ?, ?, ?)').run(app_id, pt, description || '', '', now)
    return NextResponse.json({ id: result.lastInsertRowid })
  }

  if (action === 'add_version') {
    const { app_id, platform_id, major_version, minor_version, patch_version, version_name, description, file_type, file_url, file_size, distribution_type, primary_url, fallback_url, signature_info, min_support_version, os_min_version, is_force_update, changelog } = body
    const result = db.prepare(`INSERT INTO app_platform_versions (app_id, platform_id, major_version, minor_version, patch_version, version_name, description, file_type, file_url, file_size, distribution_type, primary_url, fallback_url, signature_info, min_support_version, os_min_version, status, is_force_update, release_date, changelog) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)`).run(
      app_id, platform_id, major_version || 0, minor_version || 0, patch_version || 0,
      version_name || `${major_version || 0}.${minor_version || 0}.${patch_version || 0}`,
      description || '', file_type || '', file_url || '', file_size || 0,
      distribution_type || '', primary_url || '', fallback_url || '', signature_info || '',
      min_support_version || '', os_min_version || '', is_force_update ? 1 : 0,
      now.substring(0, 10), JSON.stringify(changelog || [])
    )
    return NextResponse.json({ id: result.lastInsertRowid })
  }

  return NextResponse.json({ error: 'unknown action' }, { status: 400 })
}

export async function PUT(req: Request) {
  seedIfEmpty()
  const db = getDb()
  const body = await req.json()
  const { action } = body
  const now = new Date().toISOString().replace('T', ' ').substring(0, 19)

  if (action === 'update_version_status') {
    const { id, status } = body
    db.prepare('UPDATE app_platform_versions SET status = ? WHERE id = ?').run(status, id)
    return NextResponse.json({ ok: true })
  }

  if (action === 'update_app') {
    const { id, name, package_name, description, status } = body
    db.prepare('UPDATE applications SET name=?, package_name=?, description=?, status=?, update_time=? WHERE id=?').run(name, package_name || '', description || '', status ?? 1, now, id)
    return NextResponse.json({ ok: true })
  }

  return NextResponse.json({ error: 'unknown action' }, { status: 400 })
}

export async function DELETE(req: NextRequest) {
  seedIfEmpty()
  const db = getDb()
  const id = req.nextUrl.searchParams.get('id')
  const type = req.nextUrl.searchParams.get('type')
  if (type === 'app' && id) {
    db.prepare('DELETE FROM app_statistics WHERE app_id = ?').run(id)
    db.prepare('DELETE FROM app_platform_versions WHERE app_id = ?').run(id)
    db.prepare('DELETE FROM app_platforms WHERE app_id = ?').run(id)
    db.prepare('DELETE FROM applications WHERE id = ?').run(id)
  }
  if (type === 'version' && id) {
    db.prepare('DELETE FROM app_platform_versions WHERE id = ?').run(id)
  }
  if (type === 'platform' && id) {
    db.prepare('DELETE FROM app_platform_versions WHERE platform_id = ?').run(id)
    db.prepare('DELETE FROM app_platforms WHERE id = ?').run(id)
  }
  return NextResponse.json({ ok: true })
}
