package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.MailSendSimpleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 메일 발송 API
 * Node.js: app.use("/api/mail/send", mailSendSimpleRoutes)
 */
@RestController
@RequestMapping("/api/mail/send")
@RequiredArgsConstructor
@Slf4j
public class MailSendSimpleController {

    private final MailSendSimpleService mailSendSimpleService;

    /**
     * POST /api/mail/send/simple — 단건 메일 발송 (첨부파일 지원)
     * multipart/form-data: accountId, to(JSON), cc(JSON), bcc(JSON),
     *   subject, templateId, customHtml, variables(JSON),
     *   modifiedTemplateComponents(JSON), fileNames(JSON), attachments[]
     */
    @PostMapping(value = "/simple",
            consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_FORM_URLENCODED_VALUE})
    public ResponseEntity<ApiResponse<Map<String, Object>>> sendMail(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam(required = false) String accountId,
            @RequestParam(required = false) String templateId,
            @RequestParam(required = false) String modifiedTemplateComponents,
            @RequestParam(required = false) String to,
            @RequestParam(required = false) String cc,
            @RequestParam(required = false) String bcc,
            @RequestParam(required = false) String subject,
            @RequestParam(required = false) String variables,
            @RequestParam(required = false) String customHtml,
            @RequestParam(required = false) String fileNames,
            @RequestPart(value = "attachments", required = false) List<MultipartFile> attachments) {

        Map<String, Object> params = new LinkedHashMap<>();
        params.put("company_code",                companyCode);
        params.put("account_id",                  accountId);
        params.put("template_id",                 templateId);
        params.put("modified_template_components", modifiedTemplateComponents);
        params.put("to",                         to);
        params.put("cc",                         cc);
        params.put("bcc",                        bcc);
        params.put("subject",                    subject);
        params.put("variables",                  variables);
        params.put("custom_html",                 customHtml);
        params.put("file_names",                  fileNames);
        params.put("attachments",                attachments);

        return ResponseEntity.ok(ApiResponse.success(
                mailSendSimpleService.sendMail(params), "메일이 발송되었습니다."));
    }

    /**
     * POST /api/mail/send/bulk — 대량 메일 발송
     * Body: { accountId, subject, templateId?, customHtml?,
     *         recipients: [{ email, variables? }] }
     */
    @PostMapping("/bulk")
    public ResponseEntity<ApiResponse<Map<String, Object>>> sendBulkMail(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {

        body.put("company_code", companyCode);
        Map<String, Object> result = mailSendSimpleService.sendBulkMail(body);
        int successCount = ((Number) result.getOrDefault("success", 0)).intValue();
        int total        = ((Number) result.getOrDefault("total",   0)).intValue();
        return ResponseEntity.ok(ApiResponse.success(result,
                successCount + "/" + total + " 건 발송 완료"));
    }

    /**
     * POST /api/mail/send/test-connection — SMTP 연결 테스트
     * Body: { accountId }
     */
    @PostMapping("/test-connection")
    public ResponseEntity<ApiResponse<Map<String, Object>>> testConnection(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {

        body.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(
                mailSendSimpleService.testConnection(body)));
    }
}
