package com.hpay.hpay_mobile_api.controllers;
import com.hpay.hpay_mobile_api.entities.MessageSujet;
import com.hpay.hpay_mobile_api.services.MessageSujetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping("/api/messages")
public class MessageSujetController {

    @Autowired
    private MessageSujetService messageSujetService;

    @GetMapping
    public Page<MessageSujet> getMessagesByClient(
            @RequestParam("idclient") Integer idClient,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String filtre // "lu" ou "nonlu"
    ) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("sujetDate").descending());

        if ("lu".equalsIgnoreCase(filtre)) {
            return messageSujetService.getMessagesByClientAndLu(idClient, "1", pageable);
        } else if ("nonlu".equalsIgnoreCase(filtre)) {
            return messageSujetService.getMessagesByClientAndLu(idClient, "0", pageable);
        } else {
            return messageSujetService.getMessagesByClient(idClient, pageable);
        }
    }


    @GetMapping("/lire/{id}")
    public ResponseEntity<MessageSujet> lireMessage(@PathVariable("id") Long id) {
        try {
            MessageSujet message = messageSujetService.markAsRead(id);
            return ResponseEntity.ok(message);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }


    @GetMapping("/nonlu/count")
    public ResponseEntity<?> countMessagesNonLus(@RequestParam("idclient") Long idClient) {
        long count = messageSujetService.countNonLusByClient(idClient);
        return ResponseEntity.ok().body(Map.of("nonLu", count));
    }

    @PostMapping("/lire-tous")
    public ResponseEntity<?> markAllAsRead(@RequestParam("idclient") Long idClient) {
        int updatedCount = messageSujetService.markAllAsReadByClient(idClient);
        return ResponseEntity.ok(Map.of("updated", updatedCount));
    }

}
