import { Response } from "express";
import { AuthenticatedRequest } from "../types/auth";
import {
  DigitalTwinTemplateService,
  DigitalTwinLayoutTemplate,
} from "../services/DigitalTwinTemplateService";

export const listMappingTemplates = async (
  req: AuthenticatedRequest,
  res: Response,
): Promise<Response> => {
  try {
    const companyCode = req.user?.companyCode;
    if (!companyCode) {
      return res.status(401).json({
        success: false,
        message: "인증 정보가 없습니다.",
      });
    }

    const externalDbConnectionId = req.query.externalDbConnectionId
      ? Number(req.query.externalDbConnectionId)
      : undefined;
    const layoutType =
      typeof req.query.layoutType === "string"
        ? req.query.layoutType
        : undefined;

    const result = await DigitalTwinTemplateService.listTemplates(
      companyCode,
      {
        externalDbConnectionId,
        layoutType,
      },
    );

    if (!result.success) {
      return res.status(500).json({
        success: false,
        message: result.message,
        error: result.error,
      });
    }

    return res.json({
      success: true,
      data: result.data as DigitalTwinLayoutTemplate[],
    });
  } catch (error: any) {
    return res.status(500).json({
      success: false,
      message: "매핑 템플릿 목록 조회 중 오류가 발생했습니다.",
      error: error.message,
    });
  }
};

export const getMappingTemplateById = async (
  req: AuthenticatedRequest,
  res: Response,
): Promise<Response> => {
  try {
    const companyCode = req.user?.companyCode;
    const { id } = req.params;

    if (!companyCode) {
      return res.status(401).json({
        success: false,
        message: "인증 정보가 없습니다.",
      });
    }

    const result = await DigitalTwinTemplateService.getTemplateById(
      companyCode,
      id,
    );

    if (!result.success) {
      return res.status(404).json({
        success: false,
        message: result.message || "매핑 템플릿을 찾을 수 없습니다.",
        error: result.error,
      });
    }

    return res.json({
      success: true,
      data: result.data,
    });
  } catch (error: any) {
    return res.status(500).json({
      success: false,
      message: "매핑 템플릿 조회 중 오류가 발생했습니다.",
      error: error.message,
    });
  }
};

export const createMappingTemplate = async (
  req: AuthenticatedRequest,
  res: Response,
): Promise<Response> => {
  try {
    const companyCode = req.user?.companyCode;
    const userId = req.user?.userId;

    if (!companyCode || !userId) {
      return res.status(401).json({
        success: false,
        message: "인증 정보가 없습니다.",
      });
    }

    const {
      name,
      description,
      externalDbConnectionId,
      layoutType,
      config,
    } = req.body;

    if (!name || !externalDbConnectionId || !config) {
      return res.status(400).json({
        success: false,
        message: "필수 필드가 누락되었습니다.",
      });
    }

    const result = await DigitalTwinTemplateService.createTemplate(
      companyCode,
      userId,
      {
        name,
        description,
        externalDbConnectionId,
        layoutType,
        config,
      },
    );

    if (!result.success || !result.data) {
      return res.status(500).json({
        success: false,
        message: result.message || "매핑 템플릿 생성 중 오류가 발생했습니다.",
        error: result.error,
      });
    }

    return res.status(201).json({
      success: true,
      data: result.data,
    });
  } catch (error: any) {
    return res.status(500).json({
      success: false,
      message: "매핑 템플릿 생성 중 오류가 발생했습니다.",
      error: error.message,
    });
  }
};




