import express from 'express'

import { BackgroundRemovalError, removeImageBackground } from './background-removal.js'
import { readMediaFile } from './media-storage.js'
import { loadAppState, saveAppState } from './storage.js'

const PORT = Number(process.env.PORT ?? 4000)
const app = express()

app.use((_request, response, next) => {
  response.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
  response.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
  response.setHeader('Cross-Origin-Resource-Policy', 'same-origin')
  next()
})

app.use(express.json({ limit: '100mb' }))

app.get('/api/health', (_request, response) => {
  response.json({ ok: true })
})

app.post(
  '/api/background-removal',
  express.raw({
    limit: '25mb',
    type: ['image/jpeg', 'image/png', 'image/webp', 'application/octet-stream']
  }),
  async (request, response, next) => {
    try {
      if (!Buffer.isBuffer(request.body) || request.body.length === 0) {
        response.status(400).json({ error: '请上传需要处理的图片' })
        return
      }

      const output = await removeImageBackground(request.body)

      response.setHeader('Cache-Control', 'no-store')
      response.setHeader('Content-Type', 'image/png')
      response.send(output)
    } catch (error) {
      next(error)
    }
  }
)

app.get('/api/storage', async (_request, response, next) => {
  try {
    response.json(await loadAppState())
  } catch (error) {
    next(error)
  }
})

app.put('/api/storage', async (request, response, next) => {
  try {
    await saveAppState(request.body)
    response.json({ ok: true })
  } catch (error) {
    next(error)
  }
})

app.get('/api/storage/media/*path', (request, response) => {
  const pathParam = request.params.path
  const segments = Array.isArray(pathParam) ? pathParam : String(pathParam).split('/')
  const media = readMediaFile(segments)

  if (!media) {
    response.status(404).send('Not found')
    return
  }

  response.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
  response.setHeader('Content-Type', media.contentType)
  response.send(media.bytes)
})

app.use((error: unknown, _request: express.Request, response: express.Response, _next: express.NextFunction) => {
  console.error(error)
  response.status(error instanceof BackgroundRemovalError ? error.statusCode : 500).json({
    error: error instanceof Error ? error.message : 'Internal server error'
  })
})

app.listen(PORT, () => {
  console.log(`Graduation API listening on http://127.0.0.1:${PORT}`)
})
