import type { APIRoute } from 'astro';
import { env } from '../../lib/env';
import { verifyCsrfToken } from '../../lib/csrf';
import { parseCookies } from '../../lib/session';
import { z } from 'zod';

const FileSchema = z.object({
  path: z.string(),
  content: z.string(),
  encoding: z.enum(['utf8', 'base64']).default('utf8'),
});
const PayloadSchema = z.object({
  message: z.string().min(1).default('Update content'),
  files: z.array(FileSchema).min(1),
});

function isAllowedPath(p: string): boolean {
  return (
    p === 'src/content/events.json' ||
    p === 'src/content/gallery.json' ||
    p === 'src/content/texts.json' ||
    p.startsWith('public/images/')
  );
}

export const POST: APIRoute = async ({ request, locals }) => {
  const user = (locals as any).user;
  if (!user) return new Response('unauthorized', { status: 401 });

  const csrf = request.headers.get('x-csrf');
  const cookies = parseCookies(request.headers.get('cookie'));
  if (!verifyCsrfToken(csrf || cookies['gp_csrf'])) {
    return new Response('bad csrf', { status: 403 });
  }

  let payload: z.infer<typeof PayloadSchema>;
  try {
    const json = await request.json();
    payload = PayloadSchema.parse(json);
  } catch (e: any) {
    return new Response('invalid payload: ' + (e?.message || e), { status: 400 });
  }

  if (!env.GITEA_BASE || !env.GITEA_OWNER || !env.GITEA_REPO || !env.GITEA_TOKEN) {
    return new Response('server not configured for Gitea', { status: 500 });
  }

  for (const f of payload.files) {
    if (!isAllowedPath(f.path)) {
      return new Response('path not allowed: ' + f.path, { status: 400 });
    }
  }

  const results: any[] = [];
  for (const f of payload.files) {
    const url = `${env.GITEA_BASE}/api/v1/repos/${encodeURIComponent(env.GITEA_OWNER!)}/${encodeURIComponent(env.GITEA_REPO!)}/contents/${encodeURIComponent(f.path)}`;
    const body: any = {
      content: f.encoding === 'base64' ? f.content : Buffer.from(f.content, 'utf-8').toString('base64'),
      message: payload.message,
      branch: env.GIT_BRANCH || 'main',
      author: {
        name: user.displayName || user.username,
        email: user.email || `${user.username}@users.noreply.local`,
      },
      committer: {
        name: user.displayName || user.username,
        email: user.email || `${user.username}@users.noreply.local`,
      }
    };

    const res = await fetch(url, {
      method: 'PUT',
      headers: {
        Authorization: `token ${env.GITEA_TOKEN}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    });
    if (!res.ok) {
      const text = await res.text();
      return new Response(`Gitea error for ${f.path}: ${res.status} ${text}`, { status: 500 });
    }
    results.push(await res.json());
  }

  return new Response(JSON.stringify({ ok: true, results }), { status: 200, headers: { 'Content-Type': 'application/json' } });
};
