'use server';

/**
 * Sales Return Server Actions
 * Server-side entry points for creating, approving, and processing sales returns
 */

import { createSalesReturnService } from '@/lib/modules/sales';
import type {
  CreateSalesReturnInput,
  ApproveSalesReturnInput,
  ReceiveSalesReturnInput,
  ProcessSalesReturnInput,
  RejectSalesReturnInput,
} from '@/lib/modules/sales';

/**
 * Create a new sales return
 */
export async function handleCreateSalesReturn(
  invoiceId: string,
  items: Array<{
    lineId: string;
    materialId: string;
    returnedQuantity: number;
    condition: 'good' | 'damaged' | 'defective' | 'faulty';
    conditionNotes?: string;
  }>,
  primaryReason: 'defective' | 'wrong_item' | 'customer_request' | 'quality_issue' | 'damaged' | 'other',
  reasonDescription: string,
  userId: string,
  userName: string,
  customerNotes?: string,
  internalNotes?: string
) {
  try {
    const service = createSalesReturnService();
    const input: CreateSalesReturnInput = {
      invoiceId,
      date: new Date().toISOString().split('T')[0],
      primaryReason,
      reasonDescription,
      items: items.map((item) => ({
        lineId: item.lineId,
        materialId: item.materialId,
        returnedQuantity: item.returnedQuantity,
        condition: item.condition,
        conditionNotes: item.conditionNotes,
        inspectionNotes: '',
      })),
      customerNotes,
      internalNotes,
      userId,
      userName,
    };

    const result = await service.create(input);
    return {
      success: true,
      data: result,
    };
  } catch (error) {
    console.error('Failed to create sales return', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

/**
 * Approve a pending return
 */
export async function handleApproveSalesReturn(
  returnId: string,
  userId: string,
  userName: string
) {
  try {
    const service = createSalesReturnService();
    const input: ApproveSalesReturnInput = {
      returnId,
      approvalDate: new Date().toISOString().split('T')[0],
      userId,
      userName,
    };

    const result = await service.approve(input);
    return {
      success: true,
      data: result,
    };
  } catch (error) {
    console.error('Failed to approve sales return', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

/**
 * Receive a returned shipment
 */
export async function handleReceiveSalesReturn(
  returnId: string,
  receivedQuantity: number,
  userId: string,
  userName: string,
  receivedNotes?: string
) {
  try {
    const service = createSalesReturnService();
    const input: ReceiveSalesReturnInput = {
      returnId,
      receivedDate: new Date().toISOString().split('T')[0],
      receivedQuantity,
      receivedNotes,
      userId,
      userName,
    };

    const result = await service.receive(input);
    return {
      success: true,
      data: result,
    };
  } catch (error) {
    console.error('Failed to receive sales return', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

/**
 * Process a return (issue credit note and refund)
 */
export async function handleProcessSalesReturn(
  returnId: string,
  refundAmount: number,
  refundMethod: 'cash' | 'check' | 'bank_transfer' | 'credit_to_account',
  userId: string,
  userName: string,
  refundReference?: string,
  processingNotes?: string
) {
  try {
    const service = createSalesReturnService();
    const input: ProcessSalesReturnInput = {
      returnId,
      processedDate: new Date().toISOString().split('T')[0],
      refundAmount,
      refundMethod,
      refundReference,
      processingNotes,
      userId,
      userName,
    };

    const result = await service.process(input);
    return {
      success: true,
      data: result,
    };
  } catch (error) {
    console.error('Failed to process sales return', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

/**
 * Reject a return
 */
export async function handleRejectSalesReturn(
  returnId: string,
  rejectionReason: string,
  userId: string,
  userName: string
) {
  try {
    const service = createSalesReturnService();
    const input: RejectSalesReturnInput = {
      returnId,
      rejectionReason,
      userId,
      userName,
    };

    const result = await service.reject(input);
    return {
      success: true,
      data: result,
    };
  } catch (error) {
    console.error('Failed to reject sales return', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

/**
 * Get all returns
 */
export async function handleGetSalesReturns() {
  try {
    const service = createSalesReturnService();
    const returns = await service.list();
    return {
      success: true,
      data: returns,
    };
  } catch (error) {
    console.error('Failed to get sales returns', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

/**
 * Get returns for a specific invoice
 */
export async function handleGetSalesReturnsByInvoice(invoiceId: string) {
  try {
    const service = createSalesReturnService();
    const returns = await service.getByInvoiceId(invoiceId);
    return {
      success: true,
      data: returns,
    };
  } catch (error) {
    console.error('Failed to get sales returns', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

/**
 * Get returns for a specific customer
 */
export async function handleGetSalesReturnsByCustomer(customerId: string) {
  try {
    const service = createSalesReturnService();
    const returns = await service.getByCustomerId(customerId);
    return {
      success: true,
      data: returns,
    };
  } catch (error) {
    console.error('Failed to get sales returns', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

/**
 * Get a specific return by ID
 */
export async function handleGetSalesReturn(returnId: string) {
  try {
    const service = createSalesReturnService();
    const salesReturn = await service.getById(returnId);
    return {
      success: true,
      data: salesReturn,
    };
  } catch (error) {
    console.error('Failed to get sales return', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}
