package dev.peerat.backend.routes.users;

import static dev.peerat.framework.RequestType.POST;

import java.util.regex.Matcher;

import dev.peerat.backend.bonus.extract.RouteDoc;
import dev.peerat.backend.model.PeerAtUser;
import dev.peerat.backend.repository.DatabaseAuthRepository;
import dev.peerat.backend.repository.DatabaseRepository;
import dev.peerat.backend.utils.FormResponse;
import dev.peerat.framework.Context;
import dev.peerat.framework.HttpReader;
import dev.peerat.framework.HttpWriter;
import dev.peerat.framework.Route;
import dev.peerat.framework.Router;
import dev.peerat.framework.utils.json.JsonMap;

public class Login extends FormResponse{

	private DatabaseAuthRepository repo;
	private Router<PeerAtUser> router;

	public Login(DatabaseRepository databaseRepo, Router<PeerAtUser> router){
		this.repo = databaseRepo.getAuthRepository();
		this.router = router;
	}
	
	@RouteDoc(path = "/login", responseCode = 200, responseDescription = "L'utilisateur est inscrit")
	@RouteDoc(responseCode = 403, responseDescription = "L'utilisateur est connecté")
	@RouteDoc(responseCode = 400, responseDescription = "Aucune données fournie / données invalide")

	@Route(path = "^\\/login$", type = POST)
	public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
		if(context.isLogged()){
			context.response(403);
			return;
		}
		JsonMap json = json(reader);
		if(!areValids("pseudo", "passwd")){
			context.response(400);
			return;
		}
		int id;
		if((id = repo.login(json.get("pseudo"), json.get("passwd"))) >= 0){
			context.response(200,
					"Access-Control-Expose-Headers: Authorization",
					"Authorization: Bearer " + this.router.createAuthUser(new PeerAtUser(id)));
		}else{
			context.response(400);
		}
	}

}
