'use server';

import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type {
  BarobillLoginFormData,
  BarobillSignupFormData,
  BankServiceFormData,
  IntegrationStatus,
  RegisteredAccount,
  RegisteredCard,
  CertificateInfo,
} from './types';

// ===== 바로빌 로그인 정보 등록 =====
export async function registerBarobillLogin(
  data: BarobillLoginFormData
): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/login'),
    method: 'POST',
    body: {
      barobill_id: data.barobillId,
      password: data.password,
    },
    errorMessage: '바로빌 로그인 등록에 실패했습니다.',
  });
}

// ===== 바로빌 회원가입 정보 등록 =====
export async function registerBarobillSignup(
  data: BarobillSignupFormData
): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/signup'),
    method: 'POST',
    body: {
      business_number: data.businessNumber,
      company_name: data.companyName,
      ceo_name: data.ceoName,
      business_type: data.businessType || undefined,
      business_category: data.businessCategory || undefined,
      address: data.address || undefined,
      barobill_id: data.barobillId,
      password: data.password,
      manager_name: data.managerName || undefined,
      manager_phone: data.managerPhone || undefined,
      manager_email: data.managerEmail || undefined,
    },
    errorMessage: '바로빌 회원가입 등록에 실패했습니다.',
  });
}

// ===== 은행 빠른조회 서비스 URL 조회 =====
export async function getBankServiceUrl(
  data: BankServiceFormData
): Promise<ActionResult<{ url: string }>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/bank-service-url', {
      bank_code: data.bankCode,
      account_type: data.accountType,
    }),
    transform: (resp: { url: string }) => ({ url: resp.url }),
    errorMessage: '은행 빠른조회 서비스 URL 조회에 실패했습니다.',
  });
}

// ===== 연동 현황 조회 =====
export async function getIntegrationStatus(): Promise<ActionResult<IntegrationStatus>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/status'),
    transform: (data: { bank_service_count?: number; account_link_count?: number; card_count?: number; member?: { barobill_id?: string; biz_no?: string; corp_name?: string; status?: string; server_mode?: string } }) => ({
      bankServiceCount: data.bank_service_count ?? 0,
      accountLinkCount: data.account_link_count ?? 0,
      cardCount: data.card_count ?? 0,
      member: data.member ? {
        barobillId: data.member.barobill_id ?? '',
        bizNo: data.member.biz_no ?? '',
        corpName: data.member.corp_name ?? '',
        status: data.member.status ?? '',
        serverMode: data.member.server_mode ?? '',
      } : undefined,
    }),
    errorMessage: '연동 현황 조회에 실패했습니다.',
  });
}

// ===== 계좌 연동 등록 URL 조회 =====
export async function getAccountLinkUrl(): Promise<ActionResult<{ url: string }>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/account-link-url'),
    transform: (resp: { url: string }) => ({ url: resp.url }),
    errorMessage: '계좌 연동 페이지 URL 조회에 실패했습니다.',
  });
}

// ===== 카드 연동 등록 URL 조회 =====
export async function getCardLinkUrl(): Promise<ActionResult<{ url: string }>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/card-link-url'),
    transform: (resp: { url: string }) => ({ url: resp.url }),
    errorMessage: '카드 연동 페이지 URL 조회에 실패했습니다.',
  });
}

// ===== 공인인증서 등록 URL 조회 =====
export async function getCertificateUrl(): Promise<ActionResult<{ url: string }>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/certificate-url'),
    transform: (resp: { url: string }) => ({ url: resp.url }),
    errorMessage: '공인인증서 등록 페이지 URL 조회에 실패했습니다.',
  });
}

// ===== 은행 거래 동기화 =====
export async function syncBankTransactions(
  startDate?: string,
  endDate?: string
): Promise<ActionResult<{ synced: number; accounts: number }>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/sync/bank'),
    method: 'POST',
    body: {
      start_date: startDate,
      end_date: endDate,
    },
    errorMessage: '은행 거래 동기화에 실패했습니다.',
  });
}

// ===== 카드 거래 동기화 =====
export async function syncCardTransactions(
  startDate?: string,
  endDate?: string
): Promise<ActionResult<{ synced: number; cards: number }>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/sync/card'),
    method: 'POST',
    body: {
      start_date: startDate,
      end_date: endDate,
    },
    errorMessage: '카드 거래 동기화에 실패했습니다.',
  });
}

// ===== 등록 계좌 목록 =====
export async function getRegisteredAccounts(): Promise<ActionResult<{
  accounts: RegisteredAccount[];
}>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/accounts'),
    errorMessage: '등록 계좌 조회에 실패했습니다.',
  });
}

// ===== 등록 카드 목록 =====
export async function getRegisteredCards(): Promise<ActionResult<{
  cards: RegisteredCard[];
}>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/cards'),
    errorMessage: '등록 카드 조회에 실패했습니다.',
  });
}

// ===== 인증서 상태 =====
export async function getCertificateStatus(): Promise<ActionResult<{
  certificate: CertificateInfo;
}>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/certificate'),
    errorMessage: '인증서 상태 조회에 실패했습니다.',
  });
}

// ===== 충전잔액 =====
export async function getBalance(): Promise<ActionResult<{ balance: number | null }>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/barobill/balance'),
    errorMessage: '충전잔액 조회에 실패했습니다.',
  });
}
