package com.example.demo.controller;

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

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

    public ArtistController() {}

    @GetMapping("/artists")
    public List<ArtistDto> getAllArtists() {
        return new ArrayList<>(artists.values());
    }

    @GetMapping("/artists/{id}")
    public ArtistDto getArtistById(@PathVariable Integer id) {
        return artists.get(id);
    }

    @PostMapping("/artists")
    public ArtistDto createArtist(@RequestBody ArtistDto artist) {
        Integer newId = idCounter.getAndIncrement();
        artist.setId(newId);
        artists.put(newId, artist);
        return artist;
    }

    @PutMapping("/artists/{id}")
    public ArtistDto updateArtist(@PathVariable Integer id, @RequestBody ArtistDto artist) {
        if (artists.containsKey(id)) {
            artist.setId(id);
            artists.put(id, artist);
            return artist;
        }
        return null;
    }

    @PatchMapping("/artists/{id}")
    public ArtistDto patchArtist(@PathVariable Integer id, @RequestBody Map<String, Object> updates) {
        ArtistDto existingArtist = artists.get(id);
        if (existingArtist != null) {
            if (updates.containsKey("name")) {
                existingArtist.setName((String) updates.get("name"));
            }
            if (updates.containsKey("description")) {
                existingArtist.setDescription((String) updates.get("description"));
            }
            if (updates.containsKey("epochId")) {
                existingArtist.setEpochId((Integer) updates.get("epochId"));
            }
            if (updates.containsKey("countryId")) {
                existingArtist.setCountryId((Integer) updates.get("countryId"));
            }
            artists.put(id, existingArtist);
            return existingArtist;
        }
        return null;
    }

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