package com.dji.sample.manage.controller;

import com.dji.sample.common.util.SecurityUtils;
import com.dji.sample.manage.model.dto.OperateRecordDTO;
import com.dji.sample.manage.service.IOperateRecordService;
import com.dji.sdk.common.HttpResultResponse;
import com.dji.sdk.common.PaginationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * REST API for querying operation records from the {@code operate_record} table.
 *
 * <p>Access control:
 * <ul>
 *   <li>ADMIN and above — can query all users' records; may also pass {@code user_id} to filter by a specific user.</li>
 *   <li>Regular users — can only see their own records; {@code user_id} param is ignored and replaced with the caller's own ID.</li>
 * </ul>
 */
@RestController
@RequestMapping("${url.manage.prefix}${url.manage.version}/operateRecord")
public class OperateRecordController {

    @Autowired
    private IOperateRecordService operateRecordService;

    /**
     * Paginated query of operation records.
     *
     * @param userId        filter by user ID (admins only; ignored for regular users)
     * @param dockSn        filter by dock SN (optional)
     * @param operatingType filter by operation type, e.g. FLIGHT_TASK_CREATE (optional)
     * @param startTime     filter start time, Unix ms (optional)
     * @param endTime       filter end time, Unix ms (optional)
     * @param page          page number, default 1
     * @param pageSize      page size, default 20
     * @return paginated list of operation records
     */
    @GetMapping("/list")
    public HttpResultResponse<PaginationData<OperateRecordDTO>> list(
            @RequestParam(name = "user_id", required = false) String userId,
            @RequestParam(required = false) String dockSn,
            @RequestParam(name = "operating_type", required = false) String operatingType,
            @RequestParam(name = "start_time", required = false) Long startTime,
            @RequestParam(name = "end_time", required = false) Long endTime,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(name = "page_size", defaultValue = "20") int pageSize) {

        String workspaceId = SecurityUtils.getWorkspaceId();

        // Admins can filter by any user; regular users are restricted to their own records.
        String effectiveUserId = SecurityUtils.aboveAdminRole() ? userId : SecurityUtils.getUserId();

        PaginationData<OperateRecordDTO> data = operateRecordService.page(
                workspaceId, effectiveUserId, dockSn, operatingType, startTime, endTime, page, pageSize);

        return HttpResultResponse.success(data);
    }
}
