package es.uv.dagarcos.master.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import es.uv.dagarcos.master.domain.MasterEvent;
import es.uv.dagarcos.master.domain.PlayerGlobal;
import es.uv.dagarcos.master.domain.Shard;
import es.uv.dagarcos.master.domain.ShardPlayerStats;
import es.uv.dagarcos.master.dto.ShardEventRequest;
import es.uv.dagarcos.master.service.MasterEventService;
import es.uv.dagarcos.master.service.PlayerGlobalService;
import es.uv.dagarcos.master.service.ShardPlayerStatsService;
import es.uv.dagarcos.master.service.ShardService;

@RestController
@RequestMapping("/master/events")
public class MasterEventController {

    @Autowired
    private ShardService shardService;
    @Autowired
    private PlayerGlobalService playerGlobalService;
    @Autowired
    private MasterEventService masterEventService;
    @Autowired
    private ShardPlayerStatsService shardPlayerStatsService;


    @PostMapping
    public ResponseEntity<Void> receiveEvent(
            @RequestBody ShardEventRequest request) {

        Shard shard = shardService.findByExternalId(request.getShardId());

        PlayerGlobal player =
                playerGlobalService.getOrCreate(request.getPlayerId());

        MasterEvent event = new MasterEvent(
                shard,
                player,
                request.getTimestamp(),
                request.getEventType(),
                request.getAction(),
                request.getPointsDelta(),
                request.getWinner(),
                request.getPayload()
        );

        masterEventService.save(event);

        ShardPlayerStats stats = shardPlayerStatsService.getOrCreate(shard, player);
        shardPlayerStatsService.applyEvent(stats, event);


        return ResponseEntity.accepted().build();
    }
}