import express, {Request, Response} from "express";
import path from "path";
import dotenv from "dotenv";
import { sendEmail } from "./email";

dotenv.config();

const app = express();
const PORT = process.env.PORT || 3070;

// 정적 파일 서빙
app.use("/", express.static(path.join(__dirname, "../dist")));
app.use("/assets", express.static(path.join(__dirname, "../dist")));

// JSON 요청을 받기 위한 미들웨어
app.use(express.json()); // application/json 파싱
app.use(express.urlencoded({ extended: true })); // application/x-www-form-urlencoded 파싱


// /request API
app.post("/request", async (req: Request, res: Response) => {
    const {
        type = "",
        phone = "",
        company_name = "",
        manager_name = "",
        email,
        budget_range,
        contents
    } = await req.body;

    if(company_name.trim().length === 0) {
        res.status(400).json({ error: "기업명을 입력하셔야 합니다." });
        return
    }

    if(manager_name.trim().length === 0) {
        res.status(400).json({ error: "담당자명을 입력하셔야 합니다." });
        return
    }

    if(type.trim().length === 0) {
        res.status(400).json({ error: "상담 분야를 입력하셔야 합니다." });
        return
    }

    if(phone.trim().length === 0) {
        res.status(400).json({ error: "연락처를 입력하셔야 합니다." });
        return
    }

    if(email.trim().length === 0) {
        res.status(400).json({ error: "이메일 주소를 입력하셔야 합니다." });
        return
    }


    if(contents.trim().length === 0) {
        res.status(400).json({ error: "문의 내용을 입력하셔야 합니다." });
        return
    }


    try {
        await sendEmail(`${type} 문의`, `
            문의 유형: ${type}
            전화번호: ${phone}
            회사명: ${company_name}
            담당자명: ${manager_name}
            이메일: ${email}
            예산 범위: ${budget_range}
            문의 내용: ${contents}
        `);
        res.json({ message: "이메일이 성공적으로 전송되었습니다." });
        return
    } catch (error) {
        console.error("이메일 전송 오류:", error);
        res.status(500).json({ error: "이메일 전송에 실패했습니다." });
        return
    }
});

app.listen(PORT, () => {
    console.log(`서버가 http://localhost:${PORT} 에서 실행 중입니다.`);
});