import * as plugins from './cloudflare.plugins.js';
import { logger } from './cloudflare.logger.js';

export interface ICloudflareRecordInfo {
  id: string;
  type: plugins.tsclass.network.TDnsRecordType;
  name: string;
  content: string;
  proxiable: boolean;
  proxied: boolean;
  ttl: number;
  locked: boolean;
  zone_id: string;
  zone_name: string;
  created_on: string;
  modified_on: string;
}

export class CloudflareRecord {
  /**
   * Create a CloudflareRecord instance from an API object
   * @param apiObject Cloudflare DNS record API object
   * @returns CloudflareRecord instance
   */
  public static createFromApiObject(apiObject: plugins.ICloudflareTypes['Record']): CloudflareRecord {
    const record = new CloudflareRecord();
    Object.assign(record, apiObject);
    return record;
  }

  // Record properties
  public id: string;
  public type: plugins.tsclass.network.TDnsRecordType;
  public name: string;
  public content: string;
  public proxiable: boolean;
  public proxied: boolean;
  public ttl: number;
  public locked: boolean;
  public zone_id: string;
  public zone_name: string;
  public created_on: string;
  public modified_on: string;

  /**
   * Update the record content
   * @param cloudflareAccount The Cloudflare account to use
   * @param newContent New content for the record
   * @param ttl Optional TTL value in seconds
   * @returns Updated record
   */
  public async update(
    cloudflareAccount: any,
    newContent: string,
    ttl?: number
  ): Promise<CloudflareRecord> {
    logger.log('info', `Updating record ${this.name} (${this.type}) with new content`);
    
    const updatedRecord = await cloudflareAccount.apiAccount.dns.records.edit(this.id, {
      zone_id: this.zone_id,
      type: this.type as any,
      name: this.name,
      content: newContent,
      ttl: ttl || this.ttl,
      proxied: this.proxied
    });
    
    // Update this instance
    this.content = newContent;
    if (ttl) {
      this.ttl = ttl;
    }
    
    return this;
  }
  
  /**
   * Delete this record
   * @param cloudflareAccount The Cloudflare account to use
   * @returns Boolean indicating success
   */
  public async delete(cloudflareAccount: any): Promise<boolean> {
    try {
      logger.log('info', `Deleting record ${this.name} (${this.type})`);
      
      await cloudflareAccount.apiAccount.dns.records.delete(this.id, {
        zone_id: this.zone_id
      });
      
      return true;
    } catch (error) {
      logger.log('error', `Failed to delete record: ${error.message}`);
      return false;
    }
  }
}