'use server';


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

// API 응답 타입
interface TenantProfile {
  id: number;
  tenant_id: number;
  user_id: number;
  department_id: number | null;
  position_key: string | null;
  job_title_key: string | null;
  department?: {
    id: number;
    name: string;
  } | null;
}

interface CardApiData {
  id: number;
  tenant_id: number;
  card_company: string;
  card_number_last4: string;
  expiry_date: string;
  card_name: string;
  status: 'active' | 'inactive';
  assigned_user_id: number | null;
  assigned_user?: {
    id: number;
    name: string;
    email?: string;
    tenant_profiles?: TenantProfile[];
  } | null;
  created_at: string;
  updated_at: string;
}

interface CardListResponse {
  success: boolean;
  message: string;
  data: {
    data: CardApiData[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
  };
}

interface CardResponse {
  success: boolean;
  message: string;
  data: CardApiData;
}

// API URL (without double /api)
const API_URL = `${process.env.NEXT_PUBLIC_API_URL}/api`;

// 상태 매핑: API → Frontend
function mapApiStatusToFrontend(apiStatus: 'active' | 'inactive'): CardStatus {
  return apiStatus === 'active' ? 'active' : 'suspended';
}

// 상태 매핑: Frontend → API
function mapFrontendStatusToApi(frontendStatus: CardStatus): 'active' | 'inactive' {
  return frontendStatus === 'active' ? 'active' : 'inactive';
}

// API → Frontend 변환
function transformApiToFrontend(apiData: CardApiData): Card {
  // TenantProfile에서 부서/직책 정보 추출
  const profile = apiData.assigned_user?.tenant_profiles?.[0];
  const department = profile?.department;

  return {
    id: String(apiData.id),
    cardCompany: apiData.card_company as Card['cardCompany'],
    cardNumber: `****-****-****-${apiData.card_number_last4}`,
    cardName: apiData.card_name,
    expiryDate: apiData.expiry_date ? apiData.expiry_date.replace('/', '') : '', // MM/YY → MMYY
    pinPrefix: '**', // 보안상 표시 안함
    status: mapApiStatusToFrontend(apiData.status),
    user: apiData.assigned_user ? {
      id: String(apiData.assigned_user.id),
      departmentId: department ? String(department.id) : '',
      departmentName: department?.name || '',
      employeeId: String(apiData.assigned_user.id),
      employeeName: apiData.assigned_user.name,
      positionId: profile?.position_key || '',
      positionName: profile?.position_key || '', // position_key를 그대로 사용 (별도 조회 필요시 추가)
    } : undefined,
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

// Frontend → API 변환
function transformFrontendToApi(data: CardFormData): Record<string, unknown> {
  const apiData: Record<string, unknown> = {
    card_company: data.cardCompany,
    expiry_date: data.expiryDate.length === 4
      ? `${data.expiryDate.slice(0, 2)}/${data.expiryDate.slice(2)}` // MMYY → MM/YY
      : data.expiryDate,
    card_name: data.cardName,
    status: mapFrontendStatusToApi(data.status),
  };

  // 카드번호가 마스킹되지 않은 경우에만 전송 (수정 시 기존 값 유지)
  const cardNumberDigits = data.cardNumber.replace(/-/g, '');
  if (cardNumberDigits && !cardNumberDigits.includes('*')) {
    apiData.card_number = cardNumberDigits;
  }

  // 비밀번호가 있으면 추가
  if (data.pinPrefix && data.pinPrefix !== '**') {
    apiData.card_password = data.pinPrefix;
  }

  // 사용자 ID가 있으면 추가
  if (data.userId) {
    apiData.assigned_user_id = parseInt(data.userId, 10);
  }

  return apiData;
}

/**
 * 카드 목록 조회
 */
export async function getCards(params?: {
  search?: string;
  status?: string;
  page?: number;
  per_page?: number;
}): Promise<{ success: boolean; data?: Card[]; pagination?: { total: number; currentPage: number; lastPage: number }; error?: string }> {
  const searchParams = new URLSearchParams();

  if (params?.search) searchParams.set('search', params.search);
  if (params?.status && params.status !== 'all') searchParams.set('status', mapFrontendStatusToApi(params.status as CardStatus));
  if (params?.page) searchParams.set('page', String(params.page));
  if (params?.per_page) searchParams.set('per_page', String(params.per_page));

  const url = `${API_URL}/v1/cards${searchParams.toString() ? `?${searchParams.toString()}` : ''}`;
  const { response, error } = await serverFetch(url, { method: 'GET' });

  if (error || !response) {
    return { success: false, error: error?.message || '카드 목록을 불러오는데 실패했습니다.' };
  }

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

  if (!result.success) {
    return { success: false, error: result.message || '카드 목록을 불러오는데 실패했습니다.' };
  }

  return {
    success: true,
    data: result.data.data.map(transformApiToFrontend),
    pagination: {
      total: result.data.total,
      currentPage: result.data.current_page,
      lastPage: result.data.last_page,
    },
  };
}

/**
 * 카드 상세 조회
 */
export async function getCard(id: string): Promise<{ success: boolean; data?: Card; error?: string }> {
  const { response, error } = await serverFetch(`${API_URL}/v1/cards/${id}`, { method: 'GET' });

  if (error || !response) {
    return { success: false, error: error?.message || '카드 정보를 불러오는데 실패했습니다.' };
  }

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

  if (!result.success) {
    return { success: false, error: result.message || '카드 정보를 불러오는데 실패했습니다.' };
  }

  return {
    success: true,
    data: transformApiToFrontend(result.data),
  };
}

/**
 * 카드 등록
 */
export async function createCard(data: CardFormData): Promise<{ success: boolean; data?: Card; error?: string }> {
  const apiData = transformFrontendToApi(data);
  const { response, error } = await serverFetch(`${API_URL}/v1/cards`, {
    method: 'POST',
    body: JSON.stringify(apiData),
  });

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

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

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

  return {
    success: true,
    data: transformApiToFrontend(result.data),
  };
}

/**
 * 카드 수정
 */
export async function updateCard(id: string, data: CardFormData): Promise<{ success: boolean; data?: Card; error?: string }> {
  const apiData = transformFrontendToApi(data);
  const { response, error } = await serverFetch(`${API_URL}/v1/cards/${id}`, {
    method: 'PUT',
    body: JSON.stringify(apiData),
  });

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

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

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

  return {
    success: true,
    data: transformApiToFrontend(result.data),
  };
}

/**
 * 카드 삭제
 */
export async function deleteCard(id: string): Promise<{ success: boolean; error?: string }> {
  const { response, error } = await serverFetch(`${API_URL}/v1/cards/${id}`, { method: 'DELETE' });

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

  const result = await response.json();

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

  return { success: true };
}

/**
 * 카드 일괄 삭제
 */
export async function deleteCards(ids: string[]): Promise<{ success: boolean; error?: string }> {
  try {
    const results = await Promise.all(ids.map(id => deleteCard(id)));
    const failed = results.filter(r => !r.success);

    if (failed.length > 0) {
      return { success: false, error: `${failed.length}개의 카드 삭제에 실패했습니다.` };
    }

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

/**
 * 카드 상태 토글
 */
export async function toggleCardStatus(id: string): Promise<{ success: boolean; data?: Card; error?: string }> {
  const { response, error } = await serverFetch(`${API_URL}/v1/cards/${id}/toggle`, { method: 'PATCH' });

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

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

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

  return {
    success: true,
    data: transformApiToFrontend(result.data),
  };
}

/**
 * 활성 직원 목록 조회 (카드 할당용)
 * 주의: Card.assigned_user_id는 User.id를 참조하므로 user.id를 반환해야 함
 */
export async function getActiveEmployees(): Promise<{ success: boolean; data?: Array<{ id: string; label: string }>; error?: string }> {
  const { response, error } = await serverFetch(`${API_URL}/v1/employees?status=active&per_page=50`, { method: 'GET' });

  if (error || !response) {
    return { success: false, error: error?.message || '직원 목록을 불러오는데 실패했습니다.' };
  }

  const result = await response.json();

  if (!result.success) {
    return { success: false, error: result.message || '직원 목록을 불러오는데 실패했습니다.' };
  }

  // API는 TenantUserProfile을 반환하지만, Card.assigned_user_id는 User.id를 참조
  // 따라서 user.id를 사용해야 함
  const employees = result.data.data.map((emp: {
    id: number;
    user_id: number;
    user?: { id: number; name: string };
    department?: { name: string };
    position_key?: string;
  }) => ({
    id: String(emp.user?.id || emp.user_id), // User.id 사용
    label: `${emp.department?.name || ''} / ${emp.user?.name || ''} / ${emp.position_key || ''}`.replace(/^ \/ | \/ $/g, '').replace(/ \/ $/g, ''),
  }));

  return { success: true, data: employees };
}