import { Account } from './account.model';
import { AccountVisitor } from './visitor.interface';

export class CsvExportVisitor implements AccountVisitor {
  private rows: string[] = [];

  constructor() {
    // Add CSV header
    this.rows.push('Service,Login,Password,Notes,UpdatedAt');
  }

  visitAccount(account: Account): void {
    const data = account.decryptedData || {};
    const service = this.escapeCsv(account.serviceName);
    const login = this.escapeCsv(data['login'] || '');
    const password = this.escapeCsv(data['password'] || '');
    const notes = this.escapeCsv(data['notes'] || '');
    const updatedAt = account.updatedAt.toISOString();

    this.rows.push(`${service},${login},${password},${notes},${updatedAt}`);
  }

  getCsv(): string {
    return this.rows.join('\n');
  }

  private escapeCsv(value: string): string {
    if (value.includes(',') || value.includes('"') || value.includes('\n')) {
      return `"${value.replace(/"/g, '""')}"`;
    }
    return value;
  }
}
