package com.fsd.hellovelo.controller;

import com.fsd.hellovelo.entity.Station;
import com.fsd.hellovelo.exceptions.ResourceNotFoundException;
import com.fsd.hellovelo.payload.request.PostalCodeRequest;
import com.fsd.hellovelo.payload.response.MessageResponse;
import com.fsd.hellovelo.service.StationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Pattern;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/stations")
public class StationUserController {

    private final StationService stationService;

    @Autowired
    public StationUserController(StationService stationService) {
        this.stationService = stationService;
    }

    @GetMapping("")
    public List<Station> getAllStations() {
        return stationService.findAllStationsUsers();
    }

    @GetMapping(path = "{stationId}")
    public ResponseEntity<?> getStation(@PathVariable("stationId") Long stationId) {
        try {
            Station station = stationService.getStationUsers(stationId);
            return ResponseEntity.status(HttpStatus.OK).body(station);
        }
        catch (ResourceNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new MessageResponse(e.getMessage()));
        }
    }

    @PostMapping("/closestStation")
    public ResponseEntity<?> getClosestStation(@RequestBody (required=false) PostalCodeRequest postalCode) {
        try{
            if(postalCode == null){
                throw new ResourceNotFoundException("Error: Invalid postal code.");
            }
            String regex = "[ABCEGHJ-NPRSTVXYabceghj-nprstvxy]\\d[ABCEGHJ-NPRSTV-Zabceghj-nprstv-z][ -]?\\d[ABCEGHJ-NPRSTV-Zabceghj-nprstv-z]\\d";
            if(!postalCode.getPostalCode().matches(regex)){
                throw new ResourceNotFoundException("Error: Invalid postal code.");
            }
            return ResponseEntity.status(HttpStatus.OK).body(stationService.getClosestStation(postalCode.getPostalCode()));
        }catch (ResourceNotFoundException ex){
            return ResponseEntity.badRequest().body(new MessageResponse(ex.getMessage()));
        }catch (IllegalArgumentException ex){
            return ResponseEntity.badRequest().body(ex.getMessage());
        }
    }

}
