/**
 * 매출 관리 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/sales - 목록 조회
 * - GET /api/v1/sales/{id} - 상세 조회
 * - POST /api/v1/sales - 등록
 * - PUT /api/v1/sales/{id} - 수정
 * - DELETE /api/v1/sales/{id} - 삭제
 * - PUT /api/v1/sales/{id}/confirm - 확정
 * - GET /api/v1/sales/summary - 요약 통계
 */

'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { serverFetch } from '@/lib/api/fetch-wrapper';
import type {
  SalesRecord,
  SaleApiData,
  SaleApiPaginatedResponse,
} from './types';
import { transformApiToFrontend, transformFrontendToApi } from './types';

// ===== 페이지네이션 타입 =====
interface PaginationMeta {
  currentPage: number;
  lastPage: number;
  perPage: number;
  total: number;
}

// ===== 매출 목록 조회 =====
export async function getSales(params?: {
  page?: number;
  perPage?: number;
  startDate?: string;
  endDate?: string;
  clientId?: string;
  status?: string;
  search?: string;
}): Promise<{
  success: boolean;
  data: SalesRecord[];
  pagination: PaginationMeta;
  error?: string;
}> {
  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?.clientId) searchParams.set('client_id', params.clientId);
  if (params?.status && params.status !== 'all') {
    searchParams.set('status', params.status);
  }
  if (params?.search) searchParams.set('search', params.search);

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

  console.log('[SalesActions] GET sales:', url);

  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('[SalesActions] GET sales 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 || '매출 목록 조회에 실패했습니다.',
    };
  }

  // API 응답 구조: { success, data: { data: [], current_page, last_page, per_page, total } }
  const paginatedData: SaleApiPaginatedResponse = result.data || {
    data: [],
    current_page: 1,
    last_page: 1,
    per_page: 20,
    total: 0,
  };

  const sales = (paginatedData.data || []).map(transformApiToFrontend);

  return {
    success: true,
    data: sales,
    pagination: {
      currentPage: paginatedData.current_page,
      lastPage: paginatedData.last_page,
      perPage: paginatedData.per_page,
      total: paginatedData.total,
    },
  };
}

// ===== 매출 상세 조회 =====
export async function getSaleById(id: string): Promise<{
  success: boolean;
  data?: SalesRecord;
  error?: string;
}> {
  const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/sales/${id}`;
  const { response, error } = await serverFetch(url, { method: 'GET' });

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

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

  const result = await response.json();

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

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

// ===== 매출 등록 =====
export async function createSale(
  data: Partial<SalesRecord>
): Promise<{ success: boolean; data?: SalesRecord; error?: string }> {
  const apiData = transformFrontendToApi(data);
  console.log('[SalesActions] POST sale request:', apiData);

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

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

  const result = await response?.json();
  console.log('[SalesActions] POST sale response:', result);

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

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

// ===== 매출 수정 =====
export async function updateSale(
  id: string,
  data: Partial<SalesRecord>
): Promise<{ success: boolean; data?: SalesRecord; error?: string }> {
  const apiData = transformFrontendToApi(data);
  console.log('[SalesActions] PUT sale request:', apiData);

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

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

  const result = await response?.json();
  console.log('[SalesActions] PUT sale response:', result);

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

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

// ===== 세금계산서/거래명세서 발행 상태 토글 =====
export async function toggleSaleIssuance(
  id: string,
  field: 'taxInvoiceIssued' | 'transactionStatementIssued',
  value: boolean
): Promise<{ success: boolean; data?: SalesRecord; error?: string }> {
  const updateData: Partial<SalesRecord> =
    field === 'taxInvoiceIssued'
      ? { taxInvoiceIssued: value }
      : { transactionStatementIssued: value };

  try {
    return await updateSale(id, updateData);
  } catch (error) {
    // 인증 만료 등으로 인한 리다이렉트 에러 → 페이지 이동 없이 에러 반환
    if (isNextRedirectError(error)) {
      return { success: false, error: '세션이 만료되었습니다. 다시 로그인해주세요.' };
    }
    throw error;
  }
}

// ===== 매출 삭제 =====
export async function deleteSale(id: string): Promise<{ success: boolean; error?: string }> {
  const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/sales/${id}`;
  const { response, error } = await serverFetch(url, { method: 'DELETE' });

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

  const result = await response?.json();
  console.log('[SalesActions] DELETE sale response:', result);

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

  return { success: true };
}

// ===== 매출 확정 =====
export async function confirmSale(id: string): Promise<{
  success: boolean;
  data?: SalesRecord;
  error?: string;
}> {
  const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/sales/${id}/confirm`;
  const { response, error } = await serverFetch(url, { method: 'PUT' });

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

  const result = await response?.json();
  console.log('[SalesActions] PUT confirm response:', result);

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

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

// ===== 매출 요약 통계 =====
export async function getSalesSummary(params?: {
  startDate?: string;
  endDate?: string;
}): Promise<{
  success: boolean;
  data?: {
    totalAmount: number;
    totalCount: number;
    confirmedAmount: number;
    confirmedCount: number;
    draftAmount: number;
    draftCount: number;
  };
  error?: string;
}> {
  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/sales/summary${queryString ? `?${queryString}` : ''}`;

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

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

  if (!response?.ok) {
    console.warn('[SalesActions] 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 || '매출 요약 조회에 실패했습니다.' };
  }

  // API 응답 → 프론트엔드 형식 변환
  const summary = result.data || {};

  return {
    success: true,
    data: {
      totalAmount: parseFloat(summary.total_amount) || 0,
      totalCount: summary.total_count || 0,
      confirmedAmount: parseFloat(summary.confirmed_amount) || 0,
      confirmedCount: summary.confirmed_count || 0,
      draftAmount: parseFloat(summary.draft_amount) || 0,
      draftCount: summary.draft_count || 0,
    },
  };
}

// ===== 계정과목 일괄 수정 =====
export async function bulkUpdateSalesAccountCode(
  ids: number[],
  accountCode: string
): Promise<{
  success: boolean;
  updatedCount?: number;
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/sales/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('[SalesActions] 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('[SalesActions] bulkUpdateSalesAccountCode error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}