package dev.peerat.backend.userstories;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;

import dev.peerat.backend.Main;
import dev.peerat.backend.WebClient;

@TestInstance(Lifecycle.PER_METHOD)
public class LoginTests extends BaseUserStoriesTest{
	
	private Thread server;
	private WebClient client;
	
	@BeforeEach
	public void init() throws Exception{
		Class.forName("com.mysql.cj.jdbc.Driver");
		
		super.init();
		getRepository().init();
		getRepository().reset();
		
		server = new Thread(new Runnable(){
			@Override
			public void run(){
				try {
					Main.main(null);
				} catch (Exception e){
					e.printStackTrace();
				};
			}
		});
		server.start();
		client = new WebClient("localhost", 80);
		
		try {
			client.register("user", "password", "mail@peerat.dev", "firstname", "lastname", "description");
			client.assertResponseCode(200);
			client.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@AfterEach
	public void stop(){
		server.interrupt();
	}
	
	@Test
	public void normalLogin() throws Exception{
		client.auth("user", "password");
		client.assertResponseCode(200);
		
	}
	
	@Test
	public void wrongPassword() throws Exception{
		client.auth("user", "password1");
		client.assertResponseCode(400);
	}
	
	@Test
	public void wrongUsername() throws Exception{
		client.auth("user1", "password");
		client.assertResponseCode(400);
	}
	
	@Test
	public void alreadyLoggedin() throws Exception{
		client.auth("user", "password");
		client.assertResponseCode(200);
		client.auth("user", "password");
		client.assertResponseCode(403);
	}
}
