// Task Team — Media Input — text, audio transcription, photo, video
const { writeFileSync, mkdirSync, existsSync } = require("fs");
const path = require("path");
const crypto = require("crypto");

const UPLOAD_DIR = "/opt/task-team/uploads";

async function mediaInputFeature(app) {
    if (!existsSync(UPLOAD_DIR)) mkdirSync(UPLOAD_DIR, { recursive: true });

    // Create media table
    await app.db.query(`
        CREATE TABLE IF NOT EXISTS media_attachments (
            id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
            task_id UUID REFERENCES tasks(id) ON DELETE CASCADE,
            user_id UUID,
            type VARCHAR(20) NOT NULL,
            filename VARCHAR(500),
            path TEXT,
            size_bytes INTEGER DEFAULT 0,
            mime_type VARCHAR(100),
            transcription TEXT,
            metadata JSONB DEFAULT '{}',
            created_at TIMESTAMPTZ DEFAULT NOW()
        )
    `).catch(() => {});

    // Upload media (base64 encoded in JSON body for simplicity)
    app.post("/media/upload", async (req) => {
        const { task_id, user_id, type, data, filename, mime_type } = req.body;
        // type: "text", "audio", "photo", "video"

        let filePath = null;
        let size = 0;
        let transcription = null;

        if (type === "text") {
            transcription = data; // plain text, no file
        } else if (data) {
            // Save base64 file
            const buffer = Buffer.from(data, "base64");
            const ext = mime_type?.split("/")[1] || type;
            const fname = crypto.randomBytes(8).toString("hex") + "." + ext;
            const dir = path.join(UPLOAD_DIR, type);
            if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
            filePath = path.join(dir, fname);
            writeFileSync(filePath, buffer);
            size = buffer.length;

            // Audio transcription via AI
            if (type === "audio" && process.env.ANTHROPIC_API_KEY) {
                transcription = "[Audio transcription pending — needs Whisper API]";
            }
        }

        const { rows } = await app.db.query(
            `INSERT INTO media_attachments (task_id, user_id, type, filename, path, size_bytes, mime_type, transcription)
             VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *`,
            [task_id, user_id, type, filename || "", filePath || "", size, mime_type || "", transcription || ""]
        );
        return { data: rows[0] };
    });

    // Get media for task
    app.get("/media/task/:taskId", async (req) => {
        const { rows } = await app.db.query(
            "SELECT id, task_id, type, filename, size_bytes, mime_type, transcription, created_at FROM media_attachments WHERE task_id=$1 ORDER BY created_at DESC",
            [req.params.taskId]
        );
        return { data: rows };
    });

    // Delete media
    app.delete("/media/:id", async (req) => {
        await app.db.query("DELETE FROM media_attachments WHERE id=$1", [req.params.id]);
        return { status: "deleted" };
    });
}
module.exports = mediaInputFeature;
