import java.time.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class LoginDemoTest {
    private static final LoginDemo.IdentityKey LOCAL =
            new LoginDemo.IdentityKey("local", "user-42");
    private static final LoginDemo.IdentityKey SSO =
            new LoginDemo.IdentityKey("https://identity.example", "employee-7");
    private static final Instant NOW = Instant.parse("2026-10-02T00:00:00Z");
    private static int passed;

    public static void main(String[] args) {
        run("valid password saves record and alert", () -> {
            var writer = new LoginDemo.InMemoryLoginWriter();
            var result = service(fixtures(), account(true), writer)
                    .login(request(LoginDemo.Method.PASSWORD, "PASSWORD_FIXTURE"));
            check(result.accountId().equals("account-42"), "Wrong account");
            check(result.method() == LoginDemo.Method.PASSWORD, "Wrong method");
            check(result.at().equals(NOW), "Clock was not used");
            check(writer.recordsCount() == 1 && writer.alertsCount() == 1,
                    "Expected record and alert");
        });
        run("valid company SSO uses the same account policy", () -> {
            var writer = new LoginDemo.InMemoryLoginWriter();
            var result = service(fixtures(), account(true), writer)
                    .login(request(LoginDemo.Method.COMPANY_SSO, "SSO_FIXTURE"));
            check(result.method() == LoginDemo.Method.COMPANY_SSO, "Wrong method");
            check(writer.recordsCount() == 1 && writer.alertsCount() == 1,
                    "Expected record and alert");
        });
        run("invalid proof never writes", () -> {
            var writer = new LoginDemo.InMemoryLoginWriter();
            expect(LoginDemo.LoginRejected.class, () ->
                    service(fixtures(), account(true), writer)
                            .login(request(LoginDemo.Method.PASSWORD, "INVALID")));
            check(writer.recordsCount() == 0 && writer.alertsCount() == 0,
                    "Rejected login wrote data");
        });
        run("disabled password account never writes", () ->
                requireDisabledRejection(LoginDemo.Method.PASSWORD, "PASSWORD_FIXTURE"));
        run("disabled SSO account never writes", () ->
                requireDisabledRejection(LoginDemo.Method.COMPANY_SSO, "SSO_FIXTURE"));
        run("unlinked identity never writes", () -> {
            var writer = new LoginDemo.InMemoryLoginWriter();
            expect(LoginDemo.LoginRejected.class, () ->
                    service(fixtures(), key -> Optional.empty(), writer)
                            .login(request(LoginDemo.Method.PASSWORD, "PASSWORD_FIXTURE")));
            check(writer.recordsCount() == 0, "Unlinked identity was admitted");
        });
        run("unsupported method is rejected", () -> {
            var passwordOnly = new LoginDemo.FixtureVerifier(Map.of(
                    LoginDemo.Method.PASSWORD, Map.of("PASSWORD_FIXTURE", LOCAL)));
            var writer = new LoginDemo.InMemoryLoginWriter();
            expect(LoginDemo.LoginRejected.class, () ->
                    service(passwordOnly, account(true), writer)
                            .login(request(LoginDemo.Method.COMPANY_SSO, "SSO_FIXTURE")));
            check(writer.recordsCount() == 0, "Unsupported method wrote data");
        });
        run("provider outage is not converted to success", () -> {
            var writer = new LoginDemo.InMemoryLoginWriter();
            LoginDemo.IdentityVerifier offline = input -> {
                throw new ProviderUnavailable();
            };
            expect(ProviderUnavailable.class, () ->
                    service(offline, account(true), writer)
                            .login(request(LoginDemo.Method.PASSWORD, "PASSWORD_FIXTURE")));
            check(writer.recordsCount() == 0, "Outage produced a login record");
        });
        run("writer failure prevents a successful return", () -> {
            var attempts = new AtomicInteger();
            LoginDemo.LoginWriter broken = (record, alert) -> {
                attempts.incrementAndGet();
                throw new LoginDemo.StorageFailure();
            };
            expect(LoginDemo.StorageFailure.class, () ->
                    service(fixtures(), account(true), broken)
                            .login(request(LoginDemo.Method.PASSWORD, "PASSWORD_FIXTURE")));
            check(attempts.get() == 1, "Writer was not reached exactly once");
        });
        run("request text redacts the proof", () -> {
            String proof = "SENSITIVE_TEST_VALUE";
            String printed = request(LoginDemo.Method.PASSWORD, proof).toString();
            check(!printed.contains(proof) && printed.contains("REDACTED"),
                    "Request text leaked proof");
        });
        run("valid verifier obeys the rejection contract", () ->
                LoginDemo.requireRejected(fixtures(),
                        request(LoginDemo.Method.PASSWORD, "INVALID")));
        run("unsafe verifier fails the same rejection contract", () ->
                expect(AssertionError.class, () ->
                        LoginDemo.requireRejected(new LoginDemo.UnsafeVerifier(LOCAL),
                                request(LoginDemo.Method.PASSWORD, "INVALID"))));
        run("verified identity requires a key", () ->
                expect(NullPointerException.class, () ->
                        new LoginDemo.VerifiedIdentity(null)));
        run("duplicate record is rejected without another alert", () -> {
            var writer = new LoginDemo.InMemoryLoginWriter();
            var record = new LoginDemo.LoginRecord(UUID.randomUUID().toString(),
                    "account-42", LoginDemo.Method.PASSWORD, NOW);
            var alert = new LoginDemo.LoginAlert(record.id(),
                    "reader@example.com", "Accepted sign-in");
            writer.save(record, alert);
            expect(IllegalStateException.class, () -> writer.save(record, alert));
            check(writer.recordsCount() == 1 && writer.alertsCount() == 1,
                    "Duplicate added data");
        });
        System.out.println("Passed: " + passed + " workflow tests");
    }

    private static void requireDisabledRejection(LoginDemo.Method method, String proof) {
        var writer = new LoginDemo.InMemoryLoginWriter();
        expect(LoginDemo.LoginRejected.class, () ->
                service(fixtures(), account(false), writer).login(request(method, proof)));
        check(writer.recordsCount() == 0 && writer.alertsCount() == 0,
                "Disabled account wrote data");
    }

    private static LoginDemo.LoginService service(LoginDemo.IdentityVerifier verifier,
            LoginDemo.AccountLookup lookup, LoginDemo.LoginWriter writer) {
        return new LoginDemo.LoginService(verifier, lookup,
                new LoginDemo.LoginPolicy(), writer,
                Clock.fixed(NOW, ZoneOffset.UTC));
    }

    private static LoginDemo.AccountLookup account(boolean enabled) {
        return key -> (key.equals(LOCAL) || key.equals(SSO))
                ? Optional.of(new LoginDemo.Account(
                        "account-42", "reader@example.com", enabled))
                : Optional.empty();
    }

    private static LoginDemo.FixtureVerifier fixtures() {
        return new LoginDemo.FixtureVerifier(Map.of(
                LoginDemo.Method.PASSWORD, Map.of("PASSWORD_FIXTURE", LOCAL),
                LoginDemo.Method.COMPANY_SSO, Map.of("SSO_FIXTURE", SSO)));
    }

    private static LoginDemo.LoginRequest request(LoginDemo.Method method, String proof) {
        return new LoginDemo.LoginRequest(method, proof);
    }

    private static void expect(Class<? extends Throwable> type, Runnable action) {
        try {
            action.run();
        } catch (Throwable failure) {
            if (type.isInstance(failure)) return;
            throw new AssertionError("Expected " + type.getSimpleName(), failure);
        }
        throw new AssertionError("Expected " + type.getSimpleName());
    }

    private static void check(boolean condition, String message) {
        if (!condition) throw new AssertionError(message);
    }

    private static void run(String name, Runnable test) {
        test.run();
        passed++;
        System.out.println("PASS " + name);
    }

    private static final class ProviderUnavailable extends RuntimeException {}
}
