package ovh.herisson.Clyde.EndPoints;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ovh.herisson.Clyde.Responses.UnauthorizedResponse;
import ovh.herisson.Clyde.Services.AuthenticatorService;
import ovh.herisson.Clyde.Services.ProtectionService;
import ovh.herisson.Clyde.Tables.InscriptionRequest;
import java.util.Date;
import java.util.Map;

@RestController
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
public class LoginController {
    private final AuthenticatorService authServ;

    static public class RequestLogin{
        private final String identifier;
        private final String password;
        @JsonFormat(pattern="yyyy-MM-dd'T'HH:mm:ss")
        private final Date expirationDate;
        public RequestLogin(String identifier, String password, Date expirationDate){
            this.identifier = identifier;
            this.password = password;
            this.expirationDate = expirationDate;
        }
    }

    public LoginController(AuthenticatorService authServ){
        this.authServ = authServ;
    }

    @PostMapping(value = "/login")
    public ResponseEntity<String> login(@RequestBody RequestLogin requestLogin){

        String sessionToken = authServ.login(requestLogin.identifier,requestLogin.password,requestLogin.expirationDate);
        if (sessionToken == null){
            return new UnauthorizedResponse<>("Identifier or Password incorrect");
        }

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Set-Cookie",String.format("session_token=%s",sessionToken));
        return ResponseEntity.ok().headers(responseHeaders).build();
    }

    @PostMapping("/register")
    public ResponseEntity<Map<String,Object>> register(@RequestBody InscriptionRequest inscriptionRequest){

        InscriptionRequest returnedInscriptionRequest = authServ.register(inscriptionRequest);

        return new ResponseEntity<>(ProtectionService.requestWithoutPassword(returnedInscriptionRequest), HttpStatus.CREATED);
    }
}
