package de.cannamanage.api.controller;

import de.cannamanage.api.dto.club.ClubResponse;
import de.cannamanage.api.dto.club.ClubStatsResponse;
import de.cannamanage.api.dto.club.UpdateClubRequest;
import de.cannamanage.domain.entity.Club;
import de.cannamanage.domain.entity.TenantContext;
import de.cannamanage.service.ClubService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@RequestMapping("/api/v1/clubs")
@RequiredArgsConstructor
@Tag(name = "Club Settings", description = "Club configuration and statistics")
public class ClubController {

    private final ClubService clubService;

    @GetMapping("/me")
    @Operation(summary = "Get current club", description = "Returns the club for the current tenant")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ClubResponse> getMyClub() {
        UUID tenantId = TenantContext.getCurrentTenant();
        Club club = clubService.getClubByTenantId(tenantId);
        return ResponseEntity.ok(toResponse(club));
    }

    @PutMapping("/me")
    @Operation(summary = "Update club settings", description = "Updates the club configuration for the current tenant")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ClubResponse> updateMyClub(@Valid @RequestBody UpdateClubRequest request) {
        UUID tenantId = TenantContext.getCurrentTenant();
        Club updated = clubService.updateClub(
                tenantId,
                request.name(),
                request.registrationNumber(),
                request.contactEmail(),
                request.contactPhone(),
                request.addressStreet(),
                request.addressCity(),
                request.addressPostalCode(),
                request.addressState(),
                request.foundedDate(),
                request.maxPreventionOfficers(),
                request.allowedEmailPattern()
        );
        return ResponseEntity.ok(toResponse(updated));
    }

    @GetMapping("/me/stats")
    @Operation(summary = "Get club statistics", description = "Returns aggregated club statistics")
    @PreAuthorize("hasRole('ADMIN') or @staffPermissions.has(authentication, T(de.cannamanage.domain.enums.StaffPermission).VIEW_COMPLIANCE_REPORT)")
    public ResponseEntity<ClubStatsResponse> getMyClubStats() {
        UUID tenantId = TenantContext.getCurrentTenant();
        ClubService.ClubStats stats = clubService.getClubStats(tenantId);
        return ResponseEntity.ok(new ClubStatsResponse(
                stats.totalMembers(),
                stats.activeMembers(),
                stats.totalStaff(),
                stats.activeStaff(),
                stats.totalDistributionsThisMonth(),
                stats.totalGramsDistributedThisMonth(),
                stats.activeBatches(),
                stats.preventionOfficerCount()
        ));
    }

    private ClubResponse toResponse(Club club) {
        return new ClubResponse(
                club.getId(),
                club.getName(),
                club.getRegistrationNumber(),
                club.getContactEmail(),
                club.getContactPhone(),
                club.getAddressStreet(),
                club.getAddressCity(),
                club.getAddressPostalCode(),
                club.getAddressState(),
                club.getFoundedDate(),
                club.getMaxPreventionOfficers(),
                club.getAllowedEmailPattern(),
                club.getStatus(),
                club.getCreatedAt()
        );
    }
}
