/**
 * Dispute Resolution Service
 * Handles worker-requester conflicts fairly
 */
'use strict';
require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

const disputes = {
  // Create a dispute
  async create(submissionId, raisedBy, reason, evidence = null) {
    const { data, error } = await supabase.from('disputes').insert({
      submission_id: submissionId,
      raised_by: raisedBy,
      reason,
      evidence,
      status: 'open',
      created_at: new Date().toISOString()
    }).select().single();
    return { data, error };
  },

  // Get dispute by submission
  async getBySubmission(submissionId) {
    const { data } = await supabase.from('disputes')
      .select('*, submission:submissions(*, task:tasks(*), worker:app_users(*)), raiser:app_users(*)')
      .eq('submission_id', submissionId)
      .single();
    return data;
  },

  // Admin resolve dispute
  async resolve(disputeId, resolution, winner, adminNotes = '') {
    const dispute = await this.getById(disputeId);
    if (!dispute) return { error: 'Dispute not found' };

    const sub = dispute.submission;
    const task = sub.task;

    // Update dispute
    await supabase.from('disputes').update({
      status: 'resolved',
      resolution,
      winner,
      admin_notes: adminNotes,
      resolved_at: new Date().toISOString()
    }).eq('id', disputeId);

    // Execute resolution
    // Use per-worker budget from submission record (worker_payment + platform_fee)
    if (winner === 'worker') {
      // Approve the submission
      await supabase.from('submissions').update({ status: 'approved', approved_at: new Date().toISOString() }).eq('id', sub.id);
      // Pay worker: move from pending to available (atomic)
      const payment = sub.worker_payment || Math.floor(task.budget * 0.8);
      await supabase.rpc('atomic_balance_op', {
        p_user_id: sub.worker_id,
        p_operation: 'release_pending',
        p_amount: payment,
      });
    } else if (winner === 'requester') {
      // Reject submission
      await supabase.from('submissions').update({ status: 'rejected', rejected_at: new Date().toISOString() }).eq('id', sub.id);
      // Refund requester (per-worker share) (atomic)
      const perWorkerBudget = (sub.worker_payment || 0) + (sub.platform_fee || 0) || task.budget;
      await supabase.rpc('atomic_balance_op', {
        p_user_id: task.requester_id,
        p_operation: 'add_available_no_earned',
        p_amount: perWorkerBudget,
      });
      // Clear worker's pending (atomic)
      const workerPmt = sub.worker_payment || Math.floor(task.budget * 0.8);
      await supabase.rpc('atomic_balance_op', {
        p_user_id: sub.worker_id,
        p_operation: 'deduct_pending',
        p_amount: workerPmt,
      });
    } else if (winner === 'split') {
      // 50/50 split
      const perWorkerBudget = (sub.worker_payment || 0) + (sub.platform_fee || 0) || task.budget;
      const halfBudget = Math.floor(perWorkerBudget / 2);
      const workerPayment = Math.floor(halfBudget * 0.8);
      // Refund half to requester (atomic)
      await supabase.rpc('atomic_balance_op', {
        p_user_id: task.requester_id,
        p_operation: 'add_available_no_earned',
        p_amount: halfBudget,
      });
      // Pay half to worker: pending → available (atomic)
      await supabase.rpc('atomic_balance_op', {
        p_user_id: sub.worker_id,
        p_operation: 'release_pending',
        p_amount: workerPayment,
      });
      // Clear remainder from pending
      const pendingRemainder = (sub.worker_payment || Math.floor(task.budget * 0.8)) - workerPayment;
      if (pendingRemainder > 0) {
        await supabase.rpc('atomic_balance_op', {
          p_user_id: sub.worker_id,
          p_operation: 'deduct_pending',
          p_amount: pendingRemainder,
        });
      }
    }

    return { success: true, resolution, winner };
  },

  // Get open disputes (for admin)
  async getOpen() {
    const { data } = await supabase.from('disputes')
      .select('*, submission:submissions(*, task:tasks(title, budget), worker:app_users(username, first_name))')
      .eq('status', 'open')
      .order('created_at', { ascending: true });
    return data || [];
  },

  async getById(id) {
    const { data } = await supabase.from('disputes')
      .select('*, submission:submissions(*, task:tasks(*), worker:app_users(*))')
      .eq('id', id)
      .single();
    return data;
  }
};

module.exports = disputes;
