import { describe, it, expect } from 'vitest';
import { computeBrokerSummary } from './stockUtils.js';

describe('computeBrokerSummary - 총 매입(total_buy) 계산', () => {
    it('총 매입 = 각 종목 매입가(purchase_price)의 단순 합 (수량 미곱산)', () => {
        const items = [
            { quantity: 100, avg_price: 72000, purchase_price: 70000, eval_amount: 7450000 },
        ];
        // 매입가 70000 (수량 곱하지 않음)
        expect(computeBrokerSummary(items).totalBuy).toBe(70_000);
    });

    it('purchase_price 미설정 시 avg_price로 폴백 (단순 합)', () => {
        const items = [
            { quantity: 100, avg_price: 72000, purchase_price: null, eval_amount: 7450000 },
        ];
        // 매입가 미입력 → 평균단가 72000 폴백
        expect(computeBrokerSummary(items).totalBuy).toBe(72_000);
    });

    it('여러 종목 합산: 각 매입가의 단순 합', () => {
        const items = [
            { quantity: 100, avg_price: 70000, purchase_price: 70000, eval_amount: 7500000 },
            { quantity: 50, avg_price: 130000, purchase_price: 130000, eval_amount: 6800000 },
        ];
        // 70000 + 130000 = 200,000 (수량 미곱산)
        expect(computeBrokerSummary(items).totalBuy).toBe(200_000);
    });

    it('손익 = 총 평가 - 매입원가(avg_price × qty) — 손익은 수량 곱산 유지', () => {
        const items = [
            { quantity: 10, avg_price: 100000, purchase_price: 90000, eval_amount: 1_200_000 },
        ];
        const s = computeBrokerSummary(items);
        // cost_basis = 100000 × 10 = 1,000,000; profit = 1,200,000 - 1,000,000 = 200,000
        expect(s.totalEval).toBe(1_200_000);
        expect(s.totalProfit).toBe(200_000);
        expect(s.totalProfitRate).toBeCloseTo(20, 5);
        expect(s.hasNullPrice).toBe(false);
    });

    it('eval_amount가 null인 종목이 있으면 hasNullPrice=true', () => {
        const items = [
            { quantity: 10, avg_price: 100000, purchase_price: 100000, eval_amount: null },
        ];
        expect(computeBrokerSummary(items).hasNullPrice).toBe(true);
    });
});
