import axios from 'axios';

interface DownloadValidationRequest {
  key: string;
  password: string;
}

interface DownloadValidationResponse {
  success: boolean;
  downloadUrl?: string;
  message?: string;
}

/**
 * Validate download password and get download URL
 * @param key - UUID key from URL parameter
 * @param password - Business registration number (사업자번호)
 * @returns Promise with download URL if validation succeeds
 */
export async function validateDownloadPassword(
  key: string,
  password: string
): Promise<DownloadValidationResponse> {
  try {
    const response = await axios.post<DownloadValidationResponse>(
      '/api/download/validate',
      {
        key,
        password,
      } as DownloadValidationRequest
    );

    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      return {
        success: false,
        message: error.response?.data?.message || '비밀번호가 일치하지 않습니다.',
      };
    }

    return {
      success: false,
      message: '오류가 발생했습니다. 다시 시도해 주세요.',
    };
  }
}

/**
 * Generate secure download link
 * @param merchantId - Merchant ID
 * @param fileType - Type of file to download
 * @returns Promise with download key and URL
 */
export async function generateDownloadLink(
  merchantId: string,
  fileType: string
): Promise<{ key: string; url: string }> {
  const response = await axios.post<{ key: string; url: string }>(
    '/api/download/generate',
    {
      merchantId,
      fileType,
    }
  );

  return response.data;
}