/**
 * Auth Types
 *
 * Types for GitHub OAuth authentication.
 */

import { z } from 'zod';

/**
 * OAuth scopes for GitHub
 */
export const DEFAULT_SCOPES = ['repo', 'read:user'];

/**
 * GitHub OAuth App Client ID (Em Dash)
 */
export const GITHUB_CLIENT_ID = 'Ov23liMPlw6JMmzUainJ';

/**
 * GitHub OAuth endpoints
 */
export const GITHUB_ENDPOINTS = {
  deviceCode: 'https://github.com/login/device/code',
  accessToken: 'https://github.com/login/oauth/access_token',
  user: 'https://api.github.com/user',
} as const;

/**
 * Auth configuration stored in config file
 */
export const AuthConfigSchema = z.object({
  access_token: z.string(),
  token_type: z.string().default('bearer'),
  scope: z.string(),
  username: z.string().optional(),
});

export type AuthConfig = z.infer<typeof AuthConfigSchema>;

/**
 * Device code response from GitHub
 */
export const DeviceCodeResponseSchema = z.object({
  device_code: z.string(),
  user_code: z.string(),
  verification_uri: z.string(),
  expires_in: z.number(),
  interval: z.number(),
});

export type DeviceCodeResponse = z.infer<typeof DeviceCodeResponseSchema>;

/**
 * Token response from GitHub
 */
export const TokenResponseSchema = z.object({
  access_token: z.string(),
  token_type: z.string(),
  scope: z.string(),
});

export type TokenResponse = z.infer<typeof TokenResponseSchema>;

/**
 * OAuth error response
 */
export const OAuthErrorSchema = z.object({
  error: z.string(),
  error_description: z.string().optional(),
  error_uri: z.string().optional(),
});

export type OAuthError = z.infer<typeof OAuthErrorSchema>;

/**
 * OAuth error codes
 */
export type OAuthErrorCode =
  | 'authorization_pending'
  | 'slow_down'
  | 'expired_token'
  | 'access_denied'
  | 'access_suspended'
  | 'unsupported_grant_type'
  | 'incorrect_client_credentials'
  | 'incorrect_device_code';

/**
 * Auth status response
 */
export interface AuthStatus {
  authenticated: boolean;
  source: 'emdash_auth' | 'environment_variable' | null;
  username?: string;
  scopes: string[];
}

/**
 * Login response for API
 */
export interface LoginResponse {
  userCode: string;
  verificationUri: string;
  expiresIn: number;
  interval: number;
}

/**
 * Poll status
 */
export type PollStatus = 'pending' | 'success' | 'expired' | 'error';

/**
 * Login poll response for API
 */
export interface LoginPollResponse {
  status: PollStatus;
  username?: string;
  error?: string;
}

/**
 * GitHub user response
 */
export interface GitHubUser {
  login: string;
  id: number;
  name?: string;
  email?: string;
}
