/**
 * TMS Authentication Service
 * Handles login and token management with MD5 password hashing
 * Persists cookies to Supabase for session recovery
 */

import axios from 'axios';
import crypto from 'crypto';
import { config } from '../config';
import { logger } from '../utils/logger';
import { supabaseService } from './supabase.service';

const TOKEN_EXPIRY = 30 * 60 * 1000; // 30 minutes

interface SessionData {
  cookies: string[];
  lastLogin: number;
}

export class AuthService {
  private static instance: AuthService;
  private cookies: string[] = [];
  private lastLogin: number = 0;
  private sessionLoaded: boolean = false;

  private constructor() {
    // Session will be loaded on first use (lazy loading)
  }

  public static getInstance(): AuthService {
    if (!AuthService.instance) {
      AuthService.instance = new AuthService();
    }
    return AuthService.instance;
  }

  /**
   * Load session from Supabase (called once on first use)
   */
  private async loadSession(): Promise<void> {
    if (this.sessionLoaded) return;
    
    try {
      const session = await supabaseService.loadTmsSession();
      
      if (session) {
        // Only use session if still valid (within expiry)
        if (Date.now() - session.lastLogin < TOKEN_EXPIRY) {
          this.cookies = session.cookies;
          this.lastLogin = session.lastLogin;
          logger.debug('✅ TMS session loaded from Supabase');
        } else {
          logger.debug('Saved TMS session expired, will login again');
          await supabaseService.deleteTmsSession();
        }
      }
    } catch (error: any) {
      logger.warn('Failed to load session from Supabase', { error: error.message });
    }
    
    this.sessionLoaded = true;
  }

  /**
   * Save session to Supabase
   */
  private async saveSession(): Promise<void> {
    await supabaseService.saveTmsSession(this.cookies, this.lastLogin);
  }

  /**
   * Login to TMS and get cookies
   * Caches cookies for 30 minutes
   */
  public async login(forceRefresh: boolean = false): Promise<string[]> {
    // Ensure session is loaded first
    await this.loadSession();
    
    // Return cached cookies if valid (unless force refresh)
    if (!forceRefresh && this.cookies.length > 0 && (Date.now() - this.lastLogin < TOKEN_EXPIRY)) {
      logger.debug('Using cached TMS cookies');
      return this.cookies;
    }

    const email = config.tmsEmail;
    const password = config.tmsPassword;

    if (!email || !password) {
      throw new Error('Missing TMS credentials in environment variables');
    }

    // MD5 hash password
    const hashedPassword = crypto.createHash('md5').update(password).digest('hex');

    try {
      logger.debug('Logging in to TMS...', { email });

      const authUrl = `${config.tmsApiUrl}/api/auth/tooning`;
      const response = await axios.post(
        authUrl,
        {
          email: email,
          password: hashedPassword,
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Origin': config.tmsApiUrl,
            'Referer': `${config.tmsApiUrl}/`,
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
          },
        }
      );

      if (response.status === 200 || response.status === 201) {
        const setCookie = response.headers['set-cookie'];
        if (setCookie) {
          this.cookies = setCookie;
          this.lastLogin = Date.now();
          await this.saveSession(); // Save to Supabase
          logger.debug('✅ TMS login successful');
          return this.cookies;
        } else {
          throw new Error('No cookies received from TMS login');
        }
      } else {
        throw new Error(`TMS login failed with status: ${response.status}`);
      }
    } catch (error: any) {
      logger.error('TMS login error', { error: error.message });
      throw error;
    }
  }

  /**
   * Get authentication headers with cookies
   */
  public async getHeaders(): Promise<Record<string, string>> {
    const cookies = await this.login();
    return {
      'Cookie': cookies.join('; '),
      'Content-Type': 'application/json',
      'Origin': config.tmsApiUrl,
      'Referer': `${config.tmsApiUrl}/`,
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    };
  }

  /**
   * Clear cached cookies (force re-login on next request)
   */
  public async clearCache(): Promise<void> {
    this.cookies = [];
    this.lastLogin = 0;
    
    // Delete session from Supabase
    await supabaseService.deleteTmsSession();
    
    logger.debug('TMS auth cache cleared');
  }
}

export const authService = AuthService.getInstance();
