package com.example.demo.controller;

import com.example.demo.dto.EpochDto;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class EpochController {
    
    private final Map<Integer, EpochDto> epochs = new LinkedHashMap<>();
    private final AtomicInteger idCounter = new AtomicInteger(1);

    public EpochController() {
        epochs.put(1, new EpochDto(1, "1980-е"));
        epochs.put(2, new EpochDto(2, "1990-е"));
    }

    @GetMapping("/epochs")
    public List<EpochDto> getAllEpochs() {
        return new ArrayList<>(epochs.values());
    }

    @GetMapping("/epochs/{id}")
    public EpochDto getEpochById(@PathVariable Integer id) {
        return epochs.get(id);
    }

    @PostMapping("/epochs")
    public EpochDto createEpoch(@RequestBody EpochDto epoch) {
        Integer newId = idCounter.getAndIncrement();
        epoch.setId(newId);
        epochs.put(newId, epoch);
        return epoch;
    }

    @PutMapping("/epochs/{id}")
    public EpochDto updateEpoch(@PathVariable Integer id, @RequestBody EpochDto epoch) {
        if (epochs.containsKey(id)) {
            epoch.setId(id);
            epochs.put(id, epoch);
            return epoch;
        }
        return null;
    }

    @PatchMapping("/epochs/{id}")
    public EpochDto patchEpoch(@PathVariable Integer id, @RequestBody Map<String, Object> updates) {
        EpochDto existingEpoch = epochs.get(id);
        if (existingEpoch != null) {
            if (updates.containsKey("name")) {
                existingEpoch.setName((String) updates.get("name"));
            }
            epochs.put(id, existingEpoch);
            return existingEpoch;
        }
        return null;
    }

    @DeleteMapping("/epochs/{id}")
    public boolean deleteEpoch(@PathVariable Integer id) {
        return epochs.remove(id) != null;
    }
}
