'use server';

import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { executePaginatedAction } from '@/lib/api/execute-paginated-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type {
  GeneralJournalRecord,
  GeneralJournalApiData,
  GeneralJournalSummary,
  GeneralJournalSummaryApiData,
  AccountSubject,
  AccountSubjectApiData,
  JournalEntryRow,
  VendorOption,
} from './types';
import {
  transformApiToFrontend,
  transformSummaryApi,
  transformAccountSubjectApi,
} from './types';

// ===== Mock 데이터 (개발용) =====
function generateMockJournalData(): GeneralJournalRecord[] {
  const descriptions = ['사무용품 구매', '직원 급여', '임대료 지급', '매출 입금', '교통비'];
  const journalDescs = ['복리후생비', '급여', '임차료', '매출', '여비교통비'];
  const divisions: Array<'deposit' | 'withdrawal' | 'transfer'> = ['deposit', 'withdrawal', 'transfer'];
  const sources: Array<'manual' | 'linked'> = ['manual', 'linked'];

  return Array.from({ length: 10 }, (_, i) => {
    const division = divisions[i % 3];
    const depositAmount = division === 'deposit' ? 100000 * (i + 1) : 0;
    const withdrawalAmount = division === 'withdrawal' ? 80000 * (i + 1) : 0;
    return {
      id: String(5000 + i),
      date: '2025-12-12',
      division,
      amount: depositAmount || withdrawalAmount || 50000,
      description: descriptions[i % 5],
      journalDescription: journalDescs[i % 5],
      depositAmount,
      withdrawalAmount,
      balance: 1000000 - (i * 50000),
      debitAmount: [6000, 100000, 50000, 0, 30000][i % 5],
      creditAmount: [0, 0, 50000, 100000, 0][i % 5],
      source: sources[i % 4 === 0 ? 0 : 1],
    };
  });
}

function generateMockSummary(): GeneralJournalSummary {
  return { totalCount: 10, depositCount: 4, depositAmount: 400000, withdrawalCount: 3, withdrawalAmount: 300000, journalCompleteCount: 7, journalIncompleteCount: 3 };
}

function generateMockAccountSubjects(): AccountSubject[] {
  return [
    { id: '101', code: '1010', name: '현금', category: 'asset', isActive: true },
    { id: '102', code: '1020', name: '보통예금', category: 'asset', isActive: true },
    { id: '201', code: '2010', name: '미지급금', category: 'liability', isActive: true },
    { id: '401', code: '4010', name: '매출', category: 'revenue', isActive: true },
    { id: '501', code: '5010', name: '복리후생비', category: 'expense', isActive: true },
  ];
}

function generateMockVendors(): VendorOption[] {
  return [
    { id: '1', name: '삼성전자' },
    { id: '2', name: '(주)한국물류' },
    { id: '3', name: 'LG전자' },
    { id: '4', name: '현대모비스' },
    { id: '5', name: '(주)대한상사' },
  ];
}

// ===== 전표 목록 조회 =====
export async function getJournalEntries(params: {
  startDate?: string;
  endDate?: string;
  search?: string;
  page?: number;
  perPage?: number;
}) {
  const result = await executePaginatedAction<GeneralJournalApiData, GeneralJournalRecord>({
    url: buildApiUrl('/api/v1/general-journal-entries', {
      start_date: params.startDate,
      end_date: params.endDate,
      search: params.search || undefined,
      page: params.page,
      per_page: params.perPage,
    }),
    transform: transformApiToFrontend,
    errorMessage: '전표 목록 조회에 실패했습니다.',
  });

  // API 실패 또는 빈 응답 시 mock fallback (개발용)
  if (!result.success || result.data.length === 0) {
    const mockData = generateMockJournalData();
    return {
      success: true as const,
      data: mockData,
      pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: mockData.length },
    };
  }
  return result;
}

// ===== 전표 요약 통계 조회 =====
export async function getJournalSummary(params: {
  startDate?: string;
  endDate?: string;
  search?: string;
}): Promise<ActionResult<GeneralJournalSummary>> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/general-journal-entries/summary', {
      start_date: params.startDate,
      end_date: params.endDate,
      search: params.search || undefined,
    }),
    transform: (data: GeneralJournalSummaryApiData) => transformSummaryApi(data),
    errorMessage: '전표 요약 조회에 실패했습니다.',
  });

  // API 실패 또는 빈 응답 시 mock fallback (개발용)
  if (!result.success || !result.data) {
    return { success: true, data: generateMockSummary() };
  }
  return result;
}

// ===== 수기 전표 등록 =====
export async function createManualJournal(data: {
  journalDate: string;
  description: string;
  rows: JournalEntryRow[];
}): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/general-journal-entries'),
    method: 'POST',
    body: {
      journal_date: data.journalDate,
      description: data.description,
      rows: data.rows.map((r) => ({
        side: r.side,
        account_subject_id: r.accountSubjectId,
        vendor_id: r.vendorId || null,
        debit_amount: r.debitAmount,
        credit_amount: r.creditAmount,
        memo: r.memo || null,
      })),
    },
    errorMessage: '수기 전표 등록에 실패했습니다.',
  });
}

// ===== 계정과목 목록 조회 =====
export async function getAccountSubjects(params?: {
  search?: string;
  category?: string;
}): Promise<ActionResult<AccountSubject[]>> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/account-subjects', {
      search: params?.search || undefined,
      category: params?.category && params.category !== 'all' ? params.category : undefined,
    }),
    transform: (data: AccountSubjectApiData[]) => data.map(transformAccountSubjectApi),
    errorMessage: '계정과목 목록 조회에 실패했습니다.',
  });

  // API 실패 또는 빈 응답 시 mock fallback (개발용)
  if (!result.success || !result.data || result.data.length === 0) {
    return { success: true, data: generateMockAccountSubjects() };
  }
  return result;
}

// ===== 계정과목 추가 =====
export async function createAccountSubject(data: {
  code: string;
  name: string;
  category: string;
}): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/account-subjects'),
    method: 'POST',
    body: {
      code: data.code,
      name: data.name,
      category: data.category,
    },
    errorMessage: '계정과목 추가에 실패했습니다.',
  });
}

// ===== 계정과목 상태 토글 =====
export async function updateAccountSubjectStatus(
  id: string,
  isActive: boolean
): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/account-subjects/${id}/status`),
    method: 'PATCH',
    body: { is_active: isActive },
    errorMessage: '계정과목 상태 변경에 실패했습니다.',
  });
}

// ===== 계정과목 삭제 =====
export async function deleteAccountSubject(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/account-subjects/${id}`),
    method: 'DELETE',
    errorMessage: '계정과목 삭제에 실패했습니다.',
  });
}

// ===== 분개 상세 조회 =====
type JournalDetailData = {
  id: number;
  date: string;
  division: string;
  amount: number;
  description: string;
  bank_name: string;
  account_number: string;
  journal_memo: string;
  rows: {
    id: number;
    side: string;
    account_subject_id: number;
    account_subject_name: string;
    vendor_id: number | null;
    vendor_name: string;
    debit_amount: number;
    credit_amount: number;
    memo: string;
  }[];
};

export async function getJournalDetail(id: string): Promise<ActionResult<JournalDetailData>> {
  const result = await executeServerAction<JournalDetailData>({
    url: buildApiUrl(`/api/v1/general-journal-entries/${id}`),
    errorMessage: '분개 상세 조회에 실패했습니다.',
  });

  // API 실패 시 mock fallback (개발용)
  if (!result.success || !result.data) {
    return {
      success: true,
      data: {
        id: Number(id),
        date: '2025-12-12',
        division: 'deposit',
        amount: 100000,
        description: '사무용품 구매',
        bank_name: '신한은행',
        account_number: '110-123-456789',
        journal_memo: '',
        rows: [
          { id: 1, side: 'debit', account_subject_id: 501, account_subject_name: '복리후생비', vendor_id: 1, vendor_name: '삼성전자', debit_amount: 100000, credit_amount: 0, memo: '' },
          { id: 2, side: 'credit', account_subject_id: 101, account_subject_name: '현금', vendor_id: null, vendor_name: '', debit_amount: 0, credit_amount: 100000, memo: '' },
        ],
      },
    };
  }
  return result;
}

// ===== 분개 수정 =====
export async function updateJournalDetail(
  id: string,
  data: {
    journalMemo: string;
    rows: JournalEntryRow[];
  }
): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/general-journal-entries/${id}/journal`),
    method: 'PUT',
    body: {
      journal_memo: data.journalMemo,
      rows: data.rows.map((r) => ({
        side: r.side,
        account_subject_id: r.accountSubjectId,
        vendor_id: r.vendorId || null,
        debit_amount: r.debitAmount,
        credit_amount: r.creditAmount,
        memo: r.memo || null,
      })),
    },
    errorMessage: '분개 수정에 실패했습니다.',
  });
}

// ===== 분개 삭제 =====
export async function deleteJournalDetail(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/general-journal-entries/${id}/journal`),
    method: 'DELETE',
    errorMessage: '분개 삭제에 실패했습니다.',
  });
}

// ===== 거래처 목록 조회 =====
export async function getVendorList(): Promise<ActionResult<VendorOption[]>> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/vendors', { per_page: 9999 }),
    transform: (data: { id: number; name: string }[]) =>
      data.map((v) => ({ id: String(v.id), name: v.name })),
    errorMessage: '거래처 목록 조회에 실패했습니다.',
  });

  // API 실패 또는 빈 응답 시 mock fallback (개발용)
  if (!result.success || !result.data || result.data.length === 0) {
    return { success: true, data: generateMockVendors() };
  }
  return result;
}
