package com.lesingle.edu.controller.parent;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lesingle.edu.entity.Clazz;
import com.lesingle.edu.entity.GrowthRecord;
import com.lesingle.edu.common.response.PageResult;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.common.security.SecurityUtils;
import com.lesingle.edu.dto.response.GrowthRecordForParentResponse;
import com.lesingle.edu.common.annotation.RequireRole;
import com.lesingle.edu.common.enums.UserRole;
import com.lesingle.edu.service.ClassService;
import com.lesingle.edu.service.GrowthRecordService;
import com.lesingle.edu.service.ParentAuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 家长端成长档案 - 只读
 * 家长仅可查看孩子的成长档案，不可创建/修改/删除
 * 返回格式对齐前端 GrowthRecord：images 为数组，recordType，class
 */
@Tag(name = "Parent - Growth Record", description = "Growth Record APIs for Parent (read-only)")
@RestController
@RequestMapping("/api/v1/parent/growth-records")
@RequiredArgsConstructor
@RequireRole(UserRole.PARENT)
public class ParentGrowthController {

    private final GrowthRecordService growthRecordService;
    private final ParentAuthService parentAuthService;
    private final ClassService classService;
    private final ObjectMapper objectMapper;

    @Operation(summary = "Get growth record by ID")
    @GetMapping("/{id}")
    public Result<GrowthRecordForParentResponse> getGrowthRecord(@PathVariable Long id) {
        Long parentId = SecurityUtils.getCurrentUserId();
        GrowthRecord record = growthRecordService.getGrowthRecordById(id);
        parentAuthService.validateParentStudentRelation(parentId, record.getStudentId());
        return Result.success(toParentResponse(record));
    }

    @Operation(summary = "Get growth records by student ID")
    @GetMapping("/student/{studentId}")
    public Result<PageResult<GrowthRecordForParentResponse>> getGrowthRecordsByStudent(
            @PathVariable Long studentId,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String type) {
        Long parentId = SecurityUtils.getCurrentUserId();
        parentAuthService.validateParentStudentRelation(parentId, studentId);
        Page<GrowthRecord> page = growthRecordService.getGrowthRecordsByStudentId(studentId, pageNum, pageSize, type);
        List<GrowthRecordForParentResponse> voList = page.getRecords().stream()
                .map(this::toParentResponse)
                .toList();
        return Result.success(PageResult.of(voList, page.getTotal(), page.getCurrent(), page.getSize()));
    }

    @Operation(summary = "Get recent growth records")
    @GetMapping("/student/{studentId}/recent")
    public Result<List<GrowthRecordForParentResponse>> getRecentGrowthRecords(
            @PathVariable Long studentId,
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        Long parentId = SecurityUtils.getCurrentUserId();
        parentAuthService.validateParentStudentRelation(parentId, studentId);
        List<GrowthRecord> records = growthRecordService.getRecentGrowthRecords(studentId, limit);
        return Result.success(records.stream().map(this::toParentResponse).toList());
    }

    private GrowthRecordForParentResponse toParentResponse(GrowthRecord record) {
        List<String> images = parseImages(record.getImages());
        GrowthRecordForParentResponse.ClassInfo classInfo = null;
        if (record.getStudentId() != null) {
            Clazz clazz = classService.getPrimaryClassByStudentId(record.getStudentId());
            if (clazz != null) {
                classInfo = GrowthRecordForParentResponse.ClassInfo.builder()
                        .id(clazz.getId())
                        .name(clazz.getName())
                        .build();
            }
        }
        return GrowthRecordForParentResponse.builder()
                .id(record.getId())
                .title(record.getTitle())
                .content(record.getContent())
                .images(images)
                .recordDate(record.getRecordDate())
                .recordType(record.getType())
                .classInfo(classInfo)
                .createdAt(record.getCreatedAt())
                .build();
    }

    private List<String> parseImages(String imagesJson) {
        if (!StringUtils.hasText(imagesJson)) {
            return Collections.emptyList();
        }
        try {
            return objectMapper.readValue(imagesJson, new TypeReference<List<String>>() {});
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }
}
