package fr.uge.concurrence;

import java.util.concurrent.ThreadLocalRandom;
import java.util.List;

public class Loto {
    public record UnscratchedTicket(long id) {}
    public record Ticket(long id, int winnings) {
        public Ticket {
            if (winnings < 0) {
                throw new IllegalArgumentException("Winnings cannot be negative");
            }
        }
    }

    public static UnscratchedTicket buy() throws InterruptedException {
        Thread.sleep(100); // Simulate time to buy a ticket
        long id = Math.abs(ThreadLocalRandom.current().nextLong());
        return new UnscratchedTicket(id);
    }

    public static Ticket scratch(UnscratchedTicket unscratchedTicket) throws InterruptedException {
        Thread.sleep(200);
        int winnings;
        double random = ThreadLocalRandom.current().nextDouble();
        if (random < 0.5) {
            winnings = 0;
        } else if (random < 0.9) {
            winnings = ThreadLocalRandom.current().nextInt(1, 1001);
        } else {
            winnings = ThreadLocalRandom.current().nextInt(1001, 10001);
        }
        return new Ticket(unscratchedTicket.id(), winnings);
    }

    public static int cashOut(List<Ticket> tickets) throws InterruptedException {
        Thread.sleep(150); // Simulate time to cash out tickets
        int total = 0;
        for (Ticket ticket : tickets) {
            total += ticket.winnings();
        }
        return total;
    }


    public static void main(String[] args) throws InterruptedException {
        UnscratchedTicket unscratchedTicket = Loto.buy();
        Ticket ticket = Loto.scratch(unscratchedTicket);
        if (ticket.winnings > 0) {
            int gain = Loto.cashOut(List.of(ticket));
            System.out.println("Gain : " + gain);
        } else {
            System.out.println("Ticket non gagnant");
        }
    }
} 
