
import express from "express";
import crypto from "crypto";
import { getDb } from "./db";
import { users, articles } from "../drizzle/schema";
import { eq } from "drizzle-orm";
import { z } from "zod";

const router = express.Router();

// Middleware d'authentification API Key
const requireApiKey = async (req: express.Request, res: express.Response, next: express.NextFunction) => {
    const apiKey = req.headers['x-api-key'];

    if (!apiKey || typeof apiKey !== 'string') {
        res.status(401).json({ error: "Missing or invalid x-api-key header" });
        return;
    }

    try {
        const db = await getDb();
        if (!db) {
            res.status(500).json({ error: "Database not available" });
            return;
        }

        const apiKeyHash = crypto.createHash("sha256").update(apiKey).digest("hex");
        const [user] = await db.select().from(users).where(eq(users.apiKeyHash, apiKeyHash));

        if (!user || user.role !== 'admin') {
            res.status(403).json({ error: "Invalid API Key or insufficient permissions" });
            return;
        }

        // Attach user to request if needed later
        (req as any).user = user;
        next();
    } catch (error) {
        console.error("API Auth Error", error);
        res.status(500).json({ error: "Internal Server Error" });
    }
};

// Validation Schema (identique à tRPC)
const articleSchema = z.object({
    title: z.string().min(5),
    slug: z.string().min(3),
    excerpt: z.string().min(20),
    content: z.string().min(100),
    heroImage: z.string().url(),
    category: z.string(),
    tags: z.array(z.string()).optional().default([]),
    author: z.string().default("Leifo"),
    published: z.boolean().default(false),
    seoKeywords: z.array(z.string()).optional().default([])
});

// Route de création d'article
router.post("/articles", requireApiKey, async (req, res) => {
    try {
        // 1. Validation de l'input
        const input = articleSchema.safeParse(req.body);

        if (!input.success) {
            res.status(400).json({ error: "Validation Error", details: input.error.flatten() });
            return;
        }

        const data = input.data;
        const db = await getDb();

        if (!db) {
            res.status(500).json({ error: "Database unavailable" });
            return;
        }

        // 2. Insertion en base
        // Note : Drizzle insère les dates automatiquement si configuré, sinon on peut ajouter createdAt
        const articleData = {
            ...data,
            tags: JSON.stringify(data.tags), // Conversion JSON pour MySQL
            seoKeywords: JSON.stringify(data.seoKeywords),
            publishedAt: data.published ? new Date() : undefined
        };

        // @ts-ignore - Insert type mismatch sometimes with specialized drizzle types
        const [result] = await db.insert(articles).values(articleData);

        res.status(201).json({
            success: true,
            message: "Article created successfully",
            id: result.insertId,
            slug: data.slug
        });

    } catch (error: any) {
        console.error("API Create Article Error", error);

        // Gestion duplicate slug
        if (error.code === 'ER_DUP_ENTRY' || error.message?.includes('Duplicate entry')) {
            res.status(409).json({ error: "An article with this slug already exists" });
            return;
        }

        res.status(500).json({ error: "Failed to create article", details: error.message });
    }
});

export const externalApiRouter = router;
