package com.lesingle.creation.controller;

import com.lesingle.creation.common.core.Result;
import com.lesingle.creation.common.security.UserPrincipal;
import com.lesingle.creation.dto.school.CreateSchoolDTO;
import com.lesingle.creation.dto.school.UpdateSchoolDTO;
import com.lesingle.creation.service.SchoolService;
import com.lesingle.creation.vo.school.SchoolVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 学校管理控制器
 */
@Tag(name = "学校管理")
@RestController
@RequestMapping("/api/schools")
@RequiredArgsConstructor
public class SchoolController {

    private final SchoolService schoolService;

    @PostMapping
    @Operation(summary = "创建学校")
    @PreAuthorize("hasAuthority('school:create')")
    public Result<SchoolVO> create(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated CreateSchoolDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        Long creatorId = userPrincipal.getUserId();
        SchoolVO result = schoolService.create(dto, tenantId, creatorId);
        return Result.success(result);
    }

    @GetMapping
    @Operation(summary = "获取学校信息")
    @PreAuthorize("hasAuthority('school:read')")
    public Result<SchoolVO> get(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long tenantId = userPrincipal.getTenantId();
        SchoolVO result = schoolService.getByTenantId(tenantId);
        return Result.success(result);
    }

    @PutMapping
    @Operation(summary = "更新学校")
    @PreAuthorize("hasAuthority('school:update')")
    public Result<SchoolVO> update(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated UpdateSchoolDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        Long modifierId = userPrincipal.getUserId();
        SchoolVO result = schoolService.update(dto, tenantId, modifierId);
        return Result.success(result);
    }

    @DeleteMapping
    @Operation(summary = "删除学校")
    @PreAuthorize("hasAuthority('school:delete')")
    public Result<Void> delete(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long tenantId = userPrincipal.getTenantId();
        schoolService.delete(tenantId);
        return Result.success();
    }
}
