package dev.ui;

import java.util.Scanner;
import dev.model.User;
import dev.service.AuthService;
import dev.service.MenuService;
import dev.service.OrderService;

public class ConsoleMenu {
    private final AuthService authService = new AuthService();
    private final MenuService menuService = new MenuService();
    private final Scanner scanner = new Scanner(System.in);
    private final OrderService orderService = new OrderService(scanner);
    private User currentUser;

    public void start() {

        while (true) {

            System.out.println();
            System.out.println("===== JAVA PIZZERIA =====");
            System.out.println("1. Login");
            System.out.println("2. Register");
            System.out.println("3. Exit");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {

                case 1:
                    login();
                    break;

                case 2:
                    register();
                    break;

                case 3: { return; }

                default:
                    System.out.println("Invalid choice");

            }

        }

    }
    private void login() {
        System.out.print("Username: ");
        String username = scanner.nextLine();
        System.out.print("Password: ");
        String password = scanner.nextLine();

        currentUser = authService.login(username, password);
        if (currentUser != null) {
            System.out.println("Login successful!");
            mainMenu();
        } else {
            System.out.println("Invalid credentials.");
        }
    }

    private void register() {
        System.out.print("Username: ");
        String username = scanner.nextLine();
        System.out.print("Password: ");
        String password = scanner.nextLine();
        System.out.print("Email: ");
        String email = scanner.nextLine();

        if (authService.register(username, password, email)) {
            System.out.println("Registration successful!");
        } else {
            System.out.println("Registration failed.");
        }
    }

    private void mainMenu() {
        while (true) {
            System.out.println("\n===== MAIN MENU =====");
            System.out.println("1. View Menu");
            System.out.println("2. Place Order");
            System.out.println("3. View Order History");
            System.out.println("4. Logout");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1 -> menuService.showMenu();
                case 2 -> orderService.placeOrder(currentUser.getId());
                case 3 -> orderService.showOrderHistory(currentUser.getId());
                case 4 -> { currentUser = null; return; }
                default -> System.out.println("Invalid choice");
            }
        }
    }
}