// peepless on Cloudflare Workers, counting into D1. Serves:
//   POST /api/peepless        the beacon (the client's default endpoint)
//   GET  /api/peepless/stats  the numbers, with Authorization: Bearer <PEEPLESS_STATS_TOKEN>
// and hands every other request to your site's static assets.
//
// Setup (see wrangler.jsonc next to this file):
//   npx wrangler d1 create peepless                  # put the id in wrangler.jsonc
//   npx wrangler d1 migrations apply peepless --remote
//   npx wrangler secret put PEEPLESS_STATS_TOKEN     # optional: a long random value
//   npx wrangler deploy
//
// Countries come from request.cf.country, which Workers always has. The rate limit is per Worker instance.
import { createHandler, createStatsHandler, d1Store } from 'peepless/server'

interface Env {
  DB: D1Database
  ASSETS: Fetcher
  PEEPLESS_STATS_TOKEN?: string
}

const projects = {
  // Your site's name, the origin it's served from, and what it may count.
  'my-app': { origin: 'https://example.com', events: ['signed_up', 'exported'], routes: ['/', '/blog/*', '/app/*'] },
}

/** request.cf.country as a lowercase code; T1 (Tor) and XX (unknown) count as no country. */
const country = (r: Request) => {
  const c = (r as { cf?: { country?: string } }).cf?.country?.toLowerCase() ?? ''
  return /^[a-z]{2}$/.test(c) && c !== 'xx' && c !== 't1' ? c : null
}

let counter: ((req: Request) => Promise<Response>) | undefined

export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const { pathname } = new URL(req.url)
    const store = d1Store(env.DB)
    // Made once per instance, so its rate limit sees more than one request. Cloudflare sets
    // cf-connecting-ip itself; x-forwarded-for can come from the client.
    if (pathname === '/api/peepless') return (counter ??= createHandler({ projects, store, address: (r) => r.headers.get('cf-connecting-ip'), country }))(req)
    if (pathname === '/api/peepless/stats') return createStatsHandler({ store, token: env.PEEPLESS_STATS_TOKEN })(req)
    return env.ASSETS.fetch(req)
  },
} satisfies ExportedHandler<Env>
