import type {LoginError} from '@/features/auth/types/auth';

/**
 * The no-JavaScript sign-in path's error vocabulary.
 *
 * When the form posts natively (see LoginCredentialsForm), the server cannot
 * hand the failure back in a JSON body — it has to redirect, and the only
 * channel a redirect has is the URL. So failures travel as a short CODE that
 * is looked up here, never as the message itself.
 *
 * That indirection is the point. A `?message=` parameter is attacker-authored
 * text rendered inside the sign-in screen: enough to forge "Your account was
 * suspended — call this number." A code that is not in this table renders
 * nothing at all, so the worst an attacker can put on the page is silence.
 *
 * Note what is absent: the email, the password, and any echo of user input.
 * The redirect carries the fact of a failure and nothing else.
 */

export const LOGIN_ERROR_PARAM = 'error';

/** Code → the field it belongs to and what the user reads. */
const LOGIN_ERRORS: Record<string, LoginError> = {
  email_required: {field: 'email', message: 'Invalid email or password.'},
  email_invalid: {field: 'email', message: 'Invalid email or password.'},
  password_required: {field: 'password', message: 'Invalid email or password.'},
  invalid_credentials: {field: 'form', message: 'Invalid email or password.'},
  malformed: {field: 'form', message: 'Sign-in failed. Please try again.'},
};

export type LoginErrorCode = keyof typeof LOGIN_ERRORS;

/** Unknown or absent codes resolve to null — render nothing, never guess. */
export function loginErrorFromCode(code: string | null): LoginError | null {
  if (!code) return null;
  return LOGIN_ERRORS[code] ?? null;
}
