'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { serverFetch } from '@/lib/api/fetch-wrapper';
import type { CardTransaction } from './types';

// ===== API 응답 타입 =====
interface CardTransactionApiItem {
  id: number;
  card_id: number | null;
  withdrawal_date: string;
  used_at: string | null;
  merchant_name: string | null;
  amount: number | string;
  account_code: string | null;
  description: string | null;
  card: {
    id: number;
    card_company: string;
    card_number_last4: string;
    card_name: string;
    assigned_user: {
      id: number;
      name: string;
    } | null;
  } | null;
  created_at: string;
  updated_at: string;
}

interface CardTransactionApiSummary {
  previous_month_total: number;
  current_month_total: number;
  total_count: number;
  total_amount: number;
}

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

// ===== API → Frontend 변환 =====
function transformItem(item: CardTransactionApiItem): CardTransaction {
  const card = item.card;
  const cardDisplay = card
    ? `${card.card_company} ${card.card_number_last4}`
    : '-';
  const cardName = card?.card_name || '-';
  const userName = card?.assigned_user?.name || '-';

  // 사용일시: used_at이 있으면 사용, 없으면 withdrawal_date + 00:00
  const usedAtRaw = item.used_at || item.withdrawal_date;
  const usedAtDate = new Date(usedAtRaw);
  const usedAt = item.used_at
    ? usedAtDate.toISOString().slice(0, 16).replace('T', ' ')
    : item.withdrawal_date;

  return {
    id: String(item.id),
    card: cardDisplay,
    cardName,
    user: userName,
    usedAt,
    merchantName: item.merchant_name || item.description || '-',
    amount: typeof item.amount === 'string' ? parseFloat(item.amount) : item.amount,
    createdAt: item.created_at,
    updatedAt: item.updated_at,
  };
}

// ===== 카드 거래 목록 조회 =====
export async function getCardTransactionList(params?: {
  page?: number;
  perPage?: number;
  startDate?: string;
  endDate?: string;
  cardId?: number;
  search?: string;
  sortBy?: string;
  sortDir?: 'asc' | 'desc';
}): Promise<{
  success: boolean;
  data: CardTransaction[];
  pagination: {
    currentPage: number;
    lastPage: number;
    perPage: number;
    total: number;
  };
  error?: string;
}> {
  try {
    const searchParams = new URLSearchParams();

    if (params?.page) searchParams.set('page', String(params.page));
    if (params?.perPage) searchParams.set('per_page', String(params.perPage));
    if (params?.startDate) searchParams.set('start_date', params.startDate);
    if (params?.endDate) searchParams.set('end_date', params.endDate);
    if (params?.cardId) searchParams.set('card_id', String(params.cardId));
    if (params?.search) searchParams.set('search', params.search);
    if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
    if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);

    const queryString = searchParams.toString();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/card-transactions${queryString ? `?${queryString}` : ''}`;

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

    if (error) {
      return {
        success: false,
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
        error: error.message,
      };
    }

    if (!response?.ok) {
      console.warn('[CardTransactionActions] GET card-transactions error:', response?.status);
      return {
        success: false,
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
        error: `API 오류: ${response?.status}`,
      };
    }

    const result = await response.json();

    if (!result.success) {
      return {
        success: false,
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
        error: result.message || '카드 거래 조회에 실패했습니다.',
      };
    }

    const paginationData = result.data;
    const items = (paginationData?.data || []).map(transformItem);
    const meta: PaginationMeta = {
      current_page: paginationData?.current_page || 1,
      last_page: paginationData?.last_page || 1,
      per_page: paginationData?.per_page || 20,
      total: paginationData?.total || items.length,
    };

    return {
      success: true,
      data: items,
      pagination: {
        currentPage: meta.current_page,
        lastPage: meta.last_page,
        perPage: meta.per_page,
        total: meta.total,
      },
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[CardTransactionActions] getCardTransactionList error:', error);
    return {
      success: false,
      data: [],
      pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 카드 거래 요약 통계 =====
export async function getCardTransactionSummary(params?: {
  startDate?: string;
  endDate?: string;
}): Promise<{
  success: boolean;
  data?: {
    previousMonthTotal: number;
    currentMonthTotal: number;
    totalCount: number;
    totalAmount: number;
  };
  error?: string;
}> {
  try {
    const searchParams = new URLSearchParams();

    if (params?.startDate) searchParams.set('start_date', params.startDate);
    if (params?.endDate) searchParams.set('end_date', params.endDate);

    const queryString = searchParams.toString();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/card-transactions/summary${queryString ? `?${queryString}` : ''}`;

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

    if (error) {
      return { success: false, error: error.message };
    }

    if (!response?.ok) {
      console.warn('[CardTransactionActions] GET summary error:', response?.status);
      return {
        success: false,
        error: `API 오류: ${response?.status}`,
      };
    }

    const result = await response.json();

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

    const apiSummary: CardTransactionApiSummary = result.data;

    return {
      success: true,
      data: {
        previousMonthTotal: apiSummary.previous_month_total,
        currentMonthTotal: apiSummary.current_month_total,
        totalCount: apiSummary.total_count,
        totalAmount: apiSummary.total_amount,
      },
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[CardTransactionActions] getCardTransactionSummary error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 카드 거래 단건 조회 =====
export async function getCardTransactionById(id: string): Promise<{
  success: boolean;
  data?: CardTransaction;
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/card-transactions/${id}`;
    const { response, error } = await serverFetch(url, { method: 'GET' });

    if (error) {
      return { success: false, error: error.message };
    }

    if (!response?.ok) {
      return { success: false, error: `API 오류: ${response?.status}` };
    }

    const result = await response.json();

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

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

// ===== 카드 거래 등록 =====
export async function createCardTransaction(data: {
  cardId?: number;
  usedAt: string;
  merchantName: string;
  amount: number;
  memo?: string;
  usageType?: string;
}): Promise<{
  success: boolean;
  data?: CardTransaction;
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/card-transactions`;
    const { response, error } = await serverFetch(url, {
      method: 'POST',
      body: JSON.stringify({
        card_id: data.cardId,
        used_at: data.usedAt,
        merchant_name: data.merchantName,
        amount: data.amount,
        description: data.memo,
        account_code: data.usageType === 'unset' ? null : data.usageType,
      }),
    });

    if (error) {
      return { success: false, error: error.message };
    }

    if (!response?.ok) {
      return { success: false, error: `API 오류: ${response?.status}` };
    }

    const result = await response.json();

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

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

// ===== 카드 거래 수정 =====
export async function updateCardTransaction(
  id: string,
  data: {
    usedAt?: string;
    merchantName?: string;
    amount?: number;
    memo?: string;
    usageType?: string;
  }
): Promise<{
  success: boolean;
  data?: CardTransaction;
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/card-transactions/${id}`;
    const { response, error } = await serverFetch(url, {
      method: 'PUT',
      body: JSON.stringify({
        used_at: data.usedAt,
        merchant_name: data.merchantName,
        amount: data.amount,
        description: data.memo,
        account_code: data.usageType === 'unset' ? null : data.usageType,
      }),
    });

    if (error) {
      return { success: false, error: error.message };
    }

    if (!response?.ok) {
      return { success: false, error: `API 오류: ${response?.status}` };
    }

    const result = await response.json();

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

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

// ===== 카드 거래 삭제 =====
export async function deleteCardTransaction(id: string): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/card-transactions/${id}`;
    const { response, error } = await serverFetch(url, { method: 'DELETE' });

    if (error) {
      return { success: false, error: error.message };
    }

    if (!response?.ok) {
      return { success: false, error: `API 오류: ${response?.status}` };
    }

    const result = await response.json();

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

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

// ===== 카드 목록 조회 (등록 폼용) =====
export async function getCardList(): Promise<{
  success: boolean;
  data: Array<{ id: number; name: string; cardNumber: string }>;
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/cards`;
    const { response, error } = await serverFetch(url, { method: 'GET' });

    if (error) {
      return { success: false, data: [], error: error.message };
    }

    if (!response?.ok) {
      return { success: false, data: [], error: `API 오류: ${response?.status}` };
    }

    const result = await response.json();

    if (!result.success) {
      return { success: false, data: [], error: result.message };
    }

    const cards = (result.data?.data || result.data || []).map((card: {
      id: number;
      card_name: string;
      card_company: string;
      card_number_last4: string;
    }) => ({
      id: card.id,
      name: card.card_name,
      cardNumber: `${card.card_company} ${card.card_number_last4}`,
    }));

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

// ===== 계정과목 일괄 수정 =====
export async function bulkUpdateAccountCode(
  ids: number[],
  accountCode: string
): Promise<{
  success: boolean;
  updatedCount?: number;
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/card-transactions/bulk-update-account`;

    const { response, error } = await serverFetch(url, {
      method: 'PUT',
      body: JSON.stringify({ ids, account_code: accountCode }),
    });

    if (error) {
      return { success: false, error: error.message };
    }

    if (!response?.ok) {
      console.warn('[CardTransactionActions] PUT bulk-update-account error:', response?.status);
      return {
        success: false,
        error: `API 오류: ${response?.status}`,
      };
    }

    const result = await response.json();

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

    return {
      success: true,
      updatedCount: result.data?.updated_count || 0,
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[CardTransactionActions] bulkUpdateAccountCode error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}