package com.example.demo.controller;

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

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

    public CountryController() {

        countries.put(1, new CountryDto(1, "Россия"));
        countries.put(2, new CountryDto(2, "США"));
        countries.put(3, new CountryDto(3, "Тайга"));
    }

    @GetMapping("/countries")
    public List<CountryDto> getAllCountries() {
        return new ArrayList<>(countries.values());
    }

    @GetMapping("/countries/{id}")
    public CountryDto getCountryById(@PathVariable Integer id) {
        return countries.get(id);
    }

    @PostMapping("/countries")
    public CountryDto createCountry(@RequestBody CountryDto country) {
        Integer newId = idCounter.getAndIncrement();
        country.setId(newId);
        countries.put(newId, country);
        return country;
    }

    @PutMapping("/countries/{id}")
    public CountryDto updateCountry(@PathVariable Integer id, @RequestBody CountryDto country) {
        if (countries.containsKey(id)) {
            country.setId(id);
            countries.put(id, country);
            return country;
        }
        return null;
    }

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

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