import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
import nodemailer from 'nodemailer';
import { spawn } from 'child_process';

export async function GET(request: NextRequest) {
    //   const token = (await cookies()).get("token")?.value
    //   if (!token) {
    //     return NextResponse.json({ success: false, message: 'Unauthorized' }, { status: 401 });
    //   }

    try {
        const params = request.nextUrl.searchParams
        const tmplid = params.get("tmpid")
        const caseid = params.get("caseid")
        const link = params.get("link")
        const rep = params.get("rep")

        if (!tmplid) {
            return NextResponse.json({ success: false, message: 'Template not found' }, { status: 404 });
        }

        const templatePath = path.join(process.cwd(), 'templates', `${tmplid}.html`);
        let template = await fs.readFile(templatePath, 'utf8');

        if (caseid) template = template.replaceAll('{{CASE_ID}}', caseid);
        if (link) template = template.replaceAll('{{LINK}}', link);
        if (rep) template = template.replaceAll('{{REP}}', rep);

        return new NextResponse(template, { headers: { 'Content-Type': 'text/html' } });
    } catch (error) {
        console.error('Error fetching template:', error);
        return NextResponse.json({ success: false, message: 'Internal server error' }, { status: 500 });
    }
}

export async function POST(request: Request): Promise<Response> {
    try {
        const { emailto, subject, tmpl, caseid, link, rep } = await request.json();
        console.log(`To: ${emailto} | Subject: ${subject} | Template: ${tmpl} | Case ID: ${caseid} | Link: ${link} | Rep: ${rep}`);

        return new Promise((resolve) => {
            const pythonExecutable = process.platform === "win32" ? "py" : "python3";
            const pythonProcess = spawn(pythonExecutable, [
                path.join(process.cwd(), "mailer.py"),
                emailto,
                subject,
                tmpl,
                caseid,
                link,
                rep
            ]);

            let output = "";
            let errorOutput = "";

            pythonProcess.stdout.on("data", (data) => {
                output += data.toString();
            });

            pythonProcess.stderr.on("data", (data) => {
                errorOutput += data.toString();
            });

            pythonProcess.on("close", (code) => {
                if (code === 0) {
                    resolve(NextResponse.json({ success: true, message: "Email sent!" }, { status: 200 }));
                } else {
                    resolve(NextResponse.json({ success: false, message: errorOutput || "Unknown error" }, { status: 500 }));
                }
            });
        });
    } catch (error) {
        console.error("Error processing request:", error);
        return NextResponse.json({ success: false, message: "Internal server error" }, { status: 500 });
    }
}
