import type { FastifyInstance } from "fastify";
import { Pool } from "pg";
import { z } from "zod";
import { config } from "../../config.js";
import { uploadToAzure } from "./azure-upload.js";

const pool = new Pool({ connectionString: config.postgresUrl });

const submitSchema = z.object({
  form_id: z.string().min(1),
  data: z.record(z.string(), z.unknown()),
  files: z.array(z.object({ url: z.string(), name: z.string() }))
});

export async function registerPocRoutes(app: FastifyInstance): Promise<void> {
  app.post("/api/poc/upload", async (request, reply) => {
    const data = await request.file();
    if (!data) return reply.code(400).send({ message: "No file provided" });

    const chunks: Buffer[] = [];
    for await (const chunk of data.file) {
      chunks.push(chunk as Buffer);
    }
    const buffer = Buffer.concat(chunks);
    const mimeType = data.mimetype ?? "application/octet-stream";

    try {
      const url = await uploadToAzure(buffer, data.filename, mimeType);
      return reply.send({ url, name: data.filename });
    } catch (err) {
      return reply.code(500).send({ message: `Upload failed: ${(err as Error).message}` });
    }
  });

  app.post("/api/poc/submit", async (request, reply) => {
    const parsed = submitSchema.safeParse(request.body);
    if (!parsed.success) return reply.code(400).send({ message: parsed.error.message });

    const { form_id, data, files } = parsed.data;
    try {
      const result = await pool.query<{ id: string; submitted_at: string }>(
        `INSERT INTO form_responses (form_id, payload, files)
         VALUES ($1, $2, $3)
         RETURNING id, submitted_at`,
        [form_id, JSON.stringify(data), JSON.stringify(files)]
      );
      const row = result.rows[0];
      return reply.code(201).send({ id: row.id, submitted_at: row.submitted_at });
    } catch (err) {
      return reply.code(500).send({ message: `Submission failed: ${(err as Error).message}` });
    }
  });
}
