import { DB } from '../db/index.js';

export class DisputeService {
  constructor(db) {
    this.db = db;
  }

  async createDispute(disputeData) {
    const { deal_id, opened_by_user_id, reason_code, summary, requested_outcome } = disputeData;
    
    const result = await this.db.query(
      `INSERT INTO disputes (deal_id, opened_by_user_id, reason_code, summary, requested_outcome) 
       VALUES (?, ?, ?, ?, ?)`,
      [deal_id, opened_by_user_id, reason_code, summary, requested_outcome]
    );
    
    const disputeId = result.insertId;
    return await this.getDisputeById(disputeId);
  }

  async getDisputeById(id) {
    const [rows] = await this.db.query('SELECT * FROM disputes WHERE id = ?', [id]);
    return rows.length > 0 ? rows[0] : null;
  }

  async updateDisputeStatus(disputeId, status, updatedByUserId) {
    await this.db.query(
      'UPDATE disputes SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [status, disputeId]
    );
    
    // Log the status change as an event
    await this.logDisputeEvent(disputeId, 'status_change', updatedByUserId, { 
      old_status: 'open', 
      new_status: status 
    });
  }

  async addEvidence(disputeId, userId, evidenceData) {
    // Log the evidence addition as an event
    await this.logDisputeEvent(disputeId, 'evidence_added', userId, evidenceData);
  }

  async resolveDispute(disputeId, resolvedByUserId, decision, reason) {
    await this.db.query(
      `UPDATE disputes 
       SET status = 'resolved', final_decision = ?, final_reason = ?, decided_by_user_id = ?, decided_at = CURRENT_TIMESTAMP 
       WHERE id = ?`,
      [decision, reason, resolvedByUserId, disputeId]
    );
    
    // Log the resolution as an event
    await this.logDisputeEvent(disputeId, 'resolved', resolvedByUserId, { decision, reason });
  }

  async logDisputeEvent(disputeId, eventType, actorUserId, payload) {
    await this.db.query(
      `INSERT INTO dispute_events (dispute_id, event_type, actor_user_id, payload_json) 
       VALUES (?, ?, ?, ?)`,
      [disputeId, eventType, actorUserId, JSON.stringify(payload)]
    );
  }

  async getDisputeEvents(disputeId) {
    const [rows] = await this.db.query('SELECT * FROM dispute_events WHERE dispute_id = ? ORDER BY created_at ASC', [disputeId]);
    return rows;
  }
}