package com.erp.controller;

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

import java.util.*;

@RestController
@RequestMapping("/api/mail-receive-basic")
@RequiredArgsConstructor
@Slf4j
public class MailReceiveBasicController {
    private final MailReceiveBasicService mailReceiveBasicService;

    /** GET /today-count → 오늘 수신 메일 수 */
    @GetMapping("/today-count")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getMailReceiveBasicTodayCount(
            @RequestAttribute("company_code") String companyCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        int count = mailReceiveBasicService.getMailReceiveBasicTodayCount(params);
        Map<String, Object> data = new HashMap<>();
        data.put("count", count);
        return ResponseEntity.ok(ApiResponse.success(data));
    }

    /** GET /{accountId}/{seqno}/attachment/{index} → 첨부파일 다운로드 */
    @GetMapping("/{accountId}/{seqno}/attachment/{index}")
    public ResponseEntity<byte[]> downloadMailReceiveBasicAttachment(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long accountId,
            @PathVariable String seqno,
            @PathVariable int index) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("account_id", accountId);
        params.put("seqno", seqno);
        params.put("attach_index", index);
        Map<String, Object> attachment = mailReceiveBasicService.getMailReceiveBasicAttachment(params);
        if (attachment == null) {
            return ResponseEntity.notFound().build();
        }
        byte[] data = (byte[]) attachment.get("content_data");
        String fileName = (String) attachment.getOrDefault("file_name", "attachment");
        String contentType = (String) attachment.getOrDefault("content_type", "application/octet-stream");
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .contentType(MediaType.parseMediaType(contentType))
                .body(data);
    }

    /** POST /{accountId}/{seqno}/mark-read → 메일 읽음 처리 */
    @PostMapping("/{accountId}/{seqno}/mark-read")
    public ResponseEntity<ApiResponse<Map<String, Object>>> markMailReceiveBasicAsRead(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long accountId,
            @PathVariable String seqno) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("account_id", accountId);
        params.put("seqno", seqno);
        return ResponseEntity.ok(ApiResponse.success(mailReceiveBasicService.markMailReceiveBasicAsRead(params)));
    }

    /** DELETE /{accountId}/{seqno} → 메일 삭제 */
    @DeleteMapping("/{accountId}/{seqno}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteMailReceiveBasic(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long accountId,
            @PathVariable String seqno) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("account_id", accountId);
        params.put("seqno", seqno);
        return ResponseEntity.ok(ApiResponse.success(mailReceiveBasicService.deleteMailReceiveBasic(params)));
    }

    /** GET /{accountId}/{seqno} → 메일 상세 조회 */
    @GetMapping("/{accountId}/{seqno}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getMailReceiveBasicInfo(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long accountId,
            @PathVariable String seqno) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("account_id", accountId);
        params.put("seqno", seqno);
        return ResponseEntity.ok(ApiResponse.success(mailReceiveBasicService.getMailReceiveBasicInfo(params)));
    }

    /** POST /{accountId}/test-imap → IMAP 연결 테스트 */
    @PostMapping("/{accountId}/test-imap")
    public ResponseEntity<ApiResponse<Map<String, Object>>> testMailReceiveBasicImapConnection(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long accountId) {
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("account_id", accountId);
        return ResponseEntity.ok(ApiResponse.success(mailReceiveBasicService.testMailReceiveBasicImapConnection(params)));
    }

    /** GET /{accountId} → 메일 목록 조회 */
    @GetMapping("/{accountId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getMailReceiveBasicList(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable Long accountId,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        params.put("account_id", accountId);
        return ResponseEntity.ok(ApiResponse.success(mailReceiveBasicService.getMailReceiveBasicList(params)));
    }
}
