'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { serverFetch } from '@/lib/api/fetch-wrapper';
import type { Account, AccountFormData, AccountStatus } from './types';
import { BANK_LABELS } from './types';

// ===== API 응답 타입 =====
interface BankAccountApiData {
  id: number;
  bank_code: string;
  bank_name: string;
  account_number: string;
  account_holder: string;
  account_name: string;
  status: AccountStatus;
  is_primary: boolean;
  assigned_user_id?: number;
  created_at?: string;
  updated_at?: string;
}

interface PaginationMeta {
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
}

interface PaginatedData {
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
  data: BankAccountApiData[];
}

interface ApiListResponse {
  success: boolean;
  message?: string;
  data: PaginatedData;
}

interface ApiSingleResponse {
  success: boolean;
  message?: string;
  data: BankAccountApiData;
}

// ===== 데이터 변환: API → Frontend =====
function transformApiToFrontend(apiData: BankAccountApiData): Account {
  return {
    id: apiData.id,
    bankCode: apiData.bank_code,
    bankName: apiData.bank_name || BANK_LABELS[apiData.bank_code] || apiData.bank_code,
    accountNumber: apiData.account_number,
    accountName: apiData.account_name,
    accountHolder: apiData.account_holder,
    status: apiData.status,
    isPrimary: apiData.is_primary,
    assignedUserId: apiData.assigned_user_id,
    createdAt: apiData.created_at || '',
    updatedAt: apiData.updated_at || '',
  };
}

// ===== 데이터 변환: Frontend → API =====
function transformFrontendToApi(data: Partial<AccountFormData>): Record<string, unknown> {
  return {
    bank_code: data.bankCode,
    bank_name: data.bankName || BANK_LABELS[data.bankCode || ''] || data.bankCode,
    account_number: data.accountNumber,
    account_holder: data.accountHolder,
    account_name: data.accountName,
    status: data.status,
  };
}

// ===== 계좌 목록 조회 =====
export async function getBankAccounts(params?: {
  page?: number;
  perPage?: number;
  search?: string;
}): Promise<{
  success: boolean;
  data?: Account[];
  meta?: PaginationMeta;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const searchParams = new URLSearchParams();

    if (params?.page) searchParams.set('page', params.page.toString());
    if (params?.perPage) searchParams.set('per_page', params.perPage.toString());
    if (params?.search) searchParams.set('search', params.search);

    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bank-accounts?${searchParams.toString()}`;

    const { response, error } = await serverFetch(url, {
      method: 'GET',
      cache: 'no-store',
    });

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return { success: false, error: '계좌 목록 조회에 실패했습니다.' };
    }

    const result: ApiListResponse = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || '계좌 목록 조회에 실패했습니다.' };
    }

    const accounts = result.data.data.map(transformApiToFrontend);
    const meta: PaginationMeta = {
      current_page: result.data.current_page,
      last_page: result.data.last_page,
      per_page: result.data.per_page,
      total: result.data.total,
    };
    return { success: true, data: accounts, meta };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[getBankAccounts] Error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 계좌 상세 조회 =====
export async function getBankAccount(id: number): Promise<{
  success: boolean;
  data?: Account;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bank-accounts/${id}`,
      {
        method: 'GET',
        cache: 'no-store',
      }
    );

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return { success: false, error: '계좌 조회에 실패했습니다.' };
    }

    const result: ApiSingleResponse = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || '계좌 조회에 실패했습니다.' };
    }

    const account = transformApiToFrontend(result.data);
    return { success: true, data: account };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[getBankAccount] Error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 계좌 생성 =====
export async function createBankAccount(data: AccountFormData): Promise<{
  success: boolean;
  data?: Account;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const apiData = transformFrontendToApi(data);

    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bank-accounts`,
      {
        method: 'POST',
        body: JSON.stringify(apiData),
      }
    );

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return { success: false, error: '계좌 등록에 실패했습니다.' };
    }

    const result: ApiSingleResponse = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || '계좌 등록에 실패했습니다.' };
    }

    const account = transformApiToFrontend(result.data);
    return { success: true, data: account };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[createBankAccount] Error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 계좌 수정 =====
export async function updateBankAccount(
  id: number,
  data: Partial<AccountFormData>
): Promise<{
  success: boolean;
  data?: Account;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const apiData = transformFrontendToApi(data);

    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bank-accounts/${id}`,
      {
        method: 'PUT',
        body: JSON.stringify(apiData),
      }
    );

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return { success: false, error: '계좌 수정에 실패했습니다.' };
    }

    const result: ApiSingleResponse = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || '계좌 수정에 실패했습니다.' };
    }

    const account = transformApiToFrontend(result.data);
    return { success: true, data: account };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[updateBankAccount] Error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 계좌 삭제 =====
export async function deleteBankAccount(id: number): Promise<{
  success: boolean;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bank-accounts/${id}`,
      {
        method: 'DELETE',
      }
    );

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return { success: false, error: '계좌 삭제에 실패했습니다.' };
    }

    const result = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || '계좌 삭제에 실패했습니다.' };
    }

    return { success: true };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[deleteBankAccount] Error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 계좌 상태 토글 =====
export async function toggleBankAccountStatus(id: number): Promise<{
  success: boolean;
  data?: Account;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bank-accounts/${id}/toggle`,
      {
        method: 'PATCH',
      }
    );

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return { success: false, error: '상태 변경에 실패했습니다.' };
    }

    const result: ApiSingleResponse = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || '상태 변경에 실패했습니다.' };
    }

    const account = transformApiToFrontend(result.data);
    return { success: true, data: account };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[toggleBankAccountStatus] Error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 대표 계좌 설정 =====
export async function setPrimaryBankAccount(id: number): Promise<{
  success: boolean;
  data?: Account;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/bank-accounts/${id}/set-primary`,
      {
        method: 'PATCH',
      }
    );

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response) {
      return { success: false, error: '대표 계좌 설정에 실패했습니다.' };
    }

    const result: ApiSingleResponse = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || '대표 계좌 설정에 실패했습니다.' };
    }

    const account = transformApiToFrontend(result.data);
    return { success: true, data: account };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[setPrimaryBankAccount] Error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 다중 삭제 =====
export async function deleteBankAccounts(ids: number[]): Promise<{
  success: boolean;
  deletedCount?: number;
  error?: string;
}> {
  try {
    const results = await Promise.all(ids.map(id => deleteBankAccount(id)));
    const successCount = results.filter(r => r.success).length;
    const failedCount = results.filter(r => !r.success).length;

    if (failedCount > 0 && successCount === 0) {
      return { success: false, error: '계좌 삭제에 실패했습니다.' };
    }

    if (failedCount > 0) {
      return {
        success: true,
        deletedCount: successCount,
        error: `${failedCount}개의 계좌 삭제에 실패했습니다.`
      };
    }

    return { success: true, deletedCount: successCount };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[deleteBankAccounts] Error:', error);
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}