package com.sino.mci.channel.controller;

import com.sino.mci.admin.security.AuthContext;
import com.sino.mci.channel.dto.CreateChannelSubjectRequest;
import com.sino.mci.channel.dto.UpdateStatusRequest;
import com.sino.mci.channel.entity.ChannelSubject;
import com.sino.mci.channel.service.ChannelSubjectService;
import com.sino.mci.shared.web.ApiResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/v1/channel-subject")
@RequiredArgsConstructor
public class ChannelSubjectController {

    private final ChannelSubjectService subjectService;

    @PostMapping
    public ApiResponse<?> createSubject(
            @RequestHeader("X-Tenant-Code") String tenantCode,
            @Valid @RequestBody CreateChannelSubjectRequest request) {
        return ApiResponse.ok(subjectService.createSubject(tenantCode, request));
    }

    @PutMapping("/{id}")
    public ApiResponse<?> updateSubject(
            @RequestHeader("X-Tenant-Code") String tenantCode,
            @PathVariable("id") Long id,
            @Valid @RequestBody CreateChannelSubjectRequest request) {
        return ApiResponse.ok(subjectService.updateSubject(id, tenantCode, request));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<?> deleteSubject(
            @RequestHeader("X-Tenant-Code") String tenantCode,
            @PathVariable("id") Long id) {
        subjectService.deleteSubject(id, tenantCode);
        return ApiResponse.ok(null);
    }

    @PatchMapping("/{id}/status")
    public ApiResponse<?> updateSubjectStatus(
            @RequestHeader("X-Tenant-Code") String tenantCode,
            @PathVariable("id") Long id,
            @Valid @RequestBody UpdateStatusRequest request) {
        return ApiResponse.ok(subjectService.updateSubjectStatus(id, tenantCode, request));
    }

    @GetMapping("/list")
    public ApiResponse<List<ChannelSubject>> listSubjects() {
        return ApiResponse.ok(subjectService.listSubjects(AuthContext.currentTenantCode()));
    }

    @PostMapping("/{id}/sync-contacts")
    public ApiResponse<com.sino.mci.channel.entity.SyncTask> syncEnterpriseContacts(
            @RequestHeader("X-Tenant-Code") String tenantCode,
            @PathVariable("id") Long id) {
        return ApiResponse.ok(subjectService.submitEnterpriseContactsSyncTask(id, tenantCode));
    }
}
