'use server';


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

const API_URL = process.env.NEXT_PUBLIC_API_URL;

// ===== 어음 목록 조회 =====
export async function getBills(params: {
  search?: string;
  billType?: string;
  status?: string;
  clientId?: string;
  isElectronic?: boolean;
  issueStartDate?: string;
  issueEndDate?: string;
  maturityStartDate?: string;
  maturityEndDate?: string;
  sortBy?: string;
  sortDir?: string;
  perPage?: number;
  page?: number;
}): Promise<{
  success: boolean;
  data: BillRecord[];
  pagination: {
    currentPage: number;
    lastPage: number;
    perPage: number;
    total: number;
  };
  error?: string;
  __authError?: boolean;
}> {
  try {
    const queryParams = new URLSearchParams();

    if (params.search) queryParams.append('search', params.search);
    if (params.billType && params.billType !== 'all') queryParams.append('bill_type', params.billType);
    if (params.status && params.status !== 'all') queryParams.append('status', params.status);
    if (params.clientId) queryParams.append('client_id', params.clientId);
    if (params.isElectronic !== undefined) queryParams.append('is_electronic', String(params.isElectronic));
    if (params.issueStartDate) queryParams.append('issue_start_date', params.issueStartDate);
    if (params.issueEndDate) queryParams.append('issue_end_date', params.issueEndDate);
    if (params.maturityStartDate) queryParams.append('maturity_start_date', params.maturityStartDate);
    if (params.maturityEndDate) queryParams.append('maturity_end_date', params.maturityEndDate);
    if (params.sortBy) queryParams.append('sort_by', params.sortBy);
    if (params.sortDir) queryParams.append('sort_dir', params.sortDir);
    if (params.perPage) queryParams.append('per_page', String(params.perPage));
    if (params.page) queryParams.append('page', String(params.page));

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

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

    if (!response) {
      return {
        success: false,
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
        error: error?.message || 'Failed to fetch bills',
      };
    }

    const result = await response.json();

    if (!response.ok || !result.success) {
      return {
        success: false,
        data: [],
        pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
        error: result.message || 'Failed to fetch bills',
      };
    }

    const paginatedData = result.data as {
      data: BillApiData[];
      current_page: number;
      last_page: number;
      per_page: number;
      total: number;
    };

    return {
      success: true,
      data: paginatedData.data.map(transformApiToFrontend),
      pagination: {
        currentPage: paginatedData.current_page,
        lastPage: paginatedData.last_page,
        perPage: paginatedData.per_page,
        total: paginatedData.total,
      },
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[getBills] Error:', error);
    return {
      success: false,
      data: [],
      pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
      error: 'Server error',
    };
  }
}

// ===== 어음 상세 조회 =====
export async function getBill(id: string): Promise<{
  success: boolean;
  data?: BillRecord;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${API_URL}/api/v1/bills/${id}`,
      { method: 'GET' }
    );

    if (error?.__authError) {
      return { success: false, __authError: true };
    }

    if (!response) {
      return { success: false, error: error?.message || 'Failed to fetch bill' };
    }

    const result = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || 'Failed to fetch bill' };
    }

    return {
      success: true,
      data: transformApiToFrontend(result.data as BillApiData),
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[getBill] Error:', error);
    return { success: false, error: 'Server error' };
  }
}

// ===== 어음 등록 =====
export async function createBill(
  data: Partial<BillRecord>
): Promise<{ success: boolean; data?: BillRecord; error?: string; __authError?: boolean }> {
  try {
    const apiData = transformFrontendToApi(data);

    console.log('[createBill] Sending data:', JSON.stringify(apiData, null, 2));

    const { response, error } = await serverFetch(
      `${API_URL}/api/v1/bills`,
      {
        method: 'POST',
        body: JSON.stringify(apiData),
      }
    );

    if (error?.__authError) {
      return { success: false, __authError: true };
    }

    if (!response) {
      return { success: false, error: error?.message || 'Failed to create bill' };
    }

    const result = await response.json();
    console.log('[createBill] Response:', result);

    if (!response.ok || !result.success) {
      if (result.errors) {
        const errorMessages = Object.values(result.errors).flat().join(', ');
        return { success: false, error: errorMessages || result.message || 'Failed to create bill' };
      }
      return { success: false, error: result.message || 'Failed to create bill' };
    }

    return {
      success: true,
      data: transformApiToFrontend(result.data as BillApiData),
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[createBill] Error:', error);
    return { success: false, error: 'Server error' };
  }
}

// ===== 어음 수정 =====
export async function updateBill(
  id: string,
  data: Partial<BillRecord>
): Promise<{ success: boolean; data?: BillRecord; error?: string; __authError?: boolean }> {
  try {
    const apiData = transformFrontendToApi(data);

    console.log('[updateBill] Sending data:', JSON.stringify(apiData, null, 2));

    const { response, error } = await serverFetch(
      `${API_URL}/api/v1/bills/${id}`,
      {
        method: 'PUT',
        body: JSON.stringify(apiData),
      }
    );

    if (error?.__authError) {
      return { success: false, __authError: true };
    }

    if (!response) {
      return { success: false, error: error?.message || 'Failed to update bill' };
    }

    const result = await response.json();
    console.log('[updateBill] Response:', result);

    if (!response.ok || !result.success) {
      if (result.errors) {
        const errorMessages = Object.values(result.errors).flat().join(', ');
        return { success: false, error: errorMessages || result.message || 'Failed to update bill' };
      }
      return { success: false, error: result.message || 'Failed to update bill' };
    }

    return {
      success: true,
      data: transformApiToFrontend(result.data as BillApiData),
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[updateBill] Error:', error);
    return { success: false, error: 'Server error' };
  }
}

// ===== 어음 삭제 =====
export async function deleteBill(id: string): Promise<{ success: boolean; error?: string; __authError?: boolean }> {
  try {
    const { response, error } = await serverFetch(
      `${API_URL}/api/v1/bills/${id}`,
      { method: 'DELETE' }
    );

    if (error?.__authError) {
      return { success: false, __authError: true };
    }

    if (!response) {
      return { success: false, error: error?.message || 'Failed to delete bill' };
    }

    const result = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || 'Failed to delete bill' };
    }

    return { success: true };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[deleteBill] Error:', error);
    return { success: false, error: 'Server error' };
  }
}

// ===== 어음 상태 변경 =====
export async function updateBillStatus(
  id: string,
  status: BillStatus
): Promise<{ success: boolean; data?: BillRecord; error?: string; __authError?: boolean }> {
  try {
    const { response, error } = await serverFetch(
      `${API_URL}/api/v1/bills/${id}/status`,
      {
        method: 'PATCH',
        body: JSON.stringify({ status }),
      }
    );

    if (error?.__authError) {
      return { success: false, __authError: true };
    }

    if (!response) {
      return { success: false, error: error?.message || 'Failed to update bill status' };
    }

    const result = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || 'Failed to update bill status' };
    }

    return {
      success: true,
      data: transformApiToFrontend(result.data as BillApiData),
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[updateBillStatus] Error:', error);
    return { success: false, error: 'Server error' };
  }
}

// ===== 어음 요약 조회 =====
export async function getBillSummary(params: {
  billType?: string;
  issueStartDate?: string;
  issueEndDate?: string;
  maturityStartDate?: string;
  maturityEndDate?: string;
}): Promise<{
  success: boolean;
  data?: {
    totalAmount: number;
    totalCount: number;
    byType: Record<string, { total: number; count: number }>;
    byStatus: Record<string, { total: number; count: number }>;
    maturityAlertAmount: number;
  };
  error?: string;
  __authError?: boolean;
}> {
  try {
    const queryParams = new URLSearchParams();

    if (params.billType && params.billType !== 'all') queryParams.append('bill_type', params.billType);
    if (params.issueStartDate) queryParams.append('issue_start_date', params.issueStartDate);
    if (params.issueEndDate) queryParams.append('issue_end_date', params.issueEndDate);
    if (params.maturityStartDate) queryParams.append('maturity_start_date', params.maturityStartDate);
    if (params.maturityEndDate) queryParams.append('maturity_end_date', params.maturityEndDate);

    const { response, error } = await serverFetch(
      `${API_URL}/api/v1/bills/summary?${queryParams.toString()}`,
      { method: 'GET' }
    );

    if (error?.__authError) {
      return { success: false, __authError: true };
    }

    if (!response) {
      return { success: false, error: error?.message || 'Failed to fetch summary' };
    }

    const result = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || 'Failed to fetch summary' };
    }

    return {
      success: true,
      data: {
        totalAmount: result.data.total_amount,
        totalCount: result.data.total_count,
        byType: result.data.by_type,
        byStatus: result.data.by_status,
        maturityAlertAmount: result.data.maturity_alert_amount,
      },
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[getBillSummary] Error:', error);
    return { success: false, error: 'Server error' };
  }
}

// ===== 거래처 목록 조회 =====
export async function getClients(): Promise<{
  success: boolean;
  data?: { id: number; name: string }[];
  error?: string;
  __authError?: boolean;
}> {
  try {
    const { response, error } = await serverFetch(
      `${API_URL}/api/v1/clients?per_page=100`,
      { method: 'GET' }
    );

    if (error?.__authError) {
      return { success: false, __authError: true };
    }

    if (!response) {
      return { success: false, error: error?.message || 'Failed to fetch clients' };
    }

    const result = await response.json();

    if (!response.ok || !result.success) {
      return { success: false, error: result.message || 'Failed to fetch clients' };
    }

    const clients = result.data?.data || result.data || [];

    return {
      success: true,
      data: clients.map((c: { id: number; name: string }) => ({
        id: c.id,
        name: c.name,
      })),
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[getClients] Error:', error);
    return { success: false, error: 'Server error' };
  }
}
