package es.uv.dagarcos.master.controller;

import es.uv.dagarcos.master.domain.Shard;
import es.uv.dagarcos.master.domain.ShardLifecycleEventType;
import es.uv.dagarcos.master.service.ShardLifecycleService;
import es.uv.dagarcos.master.service.ShardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/master/shards")
public class ShardRegistrationController {

    @Autowired
    private ShardService shardService;
    @Autowired
    private ShardLifecycleService lifecycleService;

    @PostMapping("/register")
    public ResponseEntity<Void> registerShard(@RequestBody String shardId) {

        Shard shard = shardService.findByExternalId(shardId);

        shardService.markStarted(shard);
        lifecycleService.registerEvent(
                shard,
                ShardLifecycleEventType.START,
                "Shard registrado"
        );

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


    @PostMapping("/{shardId}/heartbeat")
    public ResponseEntity<Void> heartbeat(@PathVariable String shardId) {

        Shard shard = shardService.findByExternalId(shardId);

        shardService.updateHeartbeat(shard);
        lifecycleService.registerEvent(
                shard,
                ShardLifecycleEventType.HEARTBEAT,
                "Heartbeat recibido"
        );

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

}

