<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ga.core.mapper.settle.TaxInvoiceMapper">

    <resultMap id="VOMap"   type="com.ga.core.vo.settle.TaxInvoiceVO"/>
    <resultMap id="RespMap" type="com.ga.core.vo.settle.TaxInvoiceResp"/>

    <!-- 조회용 컬럼 목록 -->
    <sql id="cols">
        ti.invoice_id,
        ti.invoice_no,
        ti.invoice_type,
        (SELECT cc.code_name FROM common_code cc
         WHERE cc.group_code = 'INVOICE_TYPE' AND cc.code = ti.invoice_type) AS invoice_type_name,
        ti.issue_date,
        ti.supply_amount,
        ti.tax_amount,
        ti.total_amount,
        ti.counterpart_name,
        ti.counterpart_biz_no,
        ti.counterpart_rep,
        ti.counterpart_addr,
        ti.agent_id,
        a.agent_name,
        ti.settle_month,
        ti.settle_id,
        ti.description,
        ti.cancel_date,
        ti.cancel_reason,
        ti.issued_by,
        u.user_name                                                           AS issued_by_name,
        ti.created_at,
        ti.updated_at
    </sql>

    <!-- 조인 절 -->
    <sql id="joins">
        FROM tax_invoice ti
        LEFT JOIN agent a ON a.agent_id = ti.agent_id
        LEFT JOIN users u ON u.user_id  = ti.issued_by
    </sql>

    <!-- 세금계산서 목록 조회 (페이징) -->
    <select id="selectList" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        <where>
            <if test="invoiceType != null and invoiceType != ''">
                AND ti.invoice_type = #{invoiceType}
            </if>
            <if test="settleMonth != null and settleMonth != ''">
                AND ti.settle_month = #{settleMonth}
            </if>
            <if test="agentId != null">AND ti.agent_id = #{agentId}</if>
            <if test="issueDateFrom != null">
                AND ti.issue_date &gt;= #{issueDateFrom}
            </if>
            <if test="issueDateTo != null">
                AND ti.issue_date &lt;= #{issueDateTo}
            </if>
            <if test="counterpartBizNo != null and counterpartBizNo != ''">
                AND ti.counterpart_biz_no = #{counterpartBizNo}
            </if>
            <!-- 취소 여부 필터 -->
            <if test="cancelledOnly != null">
                <choose>
                    <when test="cancelledOnly == true">AND ti.cancel_date IS NOT NULL</when>
                    <otherwise>AND ti.cancel_date IS NULL</otherwise>
                </choose>
            </if>
        </where>
        ORDER BY ti.issue_date DESC, ti.invoice_id DESC
    </select>

    <!-- 세금계산서 단건 조회 (응답) -->
    <select id="selectById" resultMap="RespMap">
        SELECT <include refid="cols"/>
        <include refid="joins"/>
        WHERE ti.invoice_id = #{invoiceId}
    </select>

    <!-- 발행 번호로 조회 (VO) -->
    <select id="selectByInvoiceNo" resultMap="VOMap">
        SELECT invoice_id, invoice_no, invoice_type, issue_date,
               supply_amount, tax_amount, total_amount,
               counterpart_name, counterpart_biz_no, counterpart_rep, counterpart_addr,
               agent_id, settle_month, settle_id,
               description, cancel_date, cancel_reason, issued_by,
               created_at, updated_at
        FROM tax_invoice WHERE invoice_no = #{invoiceNo}
    </select>

    <!-- 정산월별 금액 합계 (SUPPLY 또는 PURCHASE) -->
    <select id="sumSupplyAmountByMonth" resultType="java.math.BigDecimal">
        SELECT COALESCE(SUM(supply_amount), 0)
        FROM tax_invoice
        WHERE settle_month  = #{settleMonth}
          AND invoice_type  = #{invoiceType}
          AND cancel_date   IS NULL  -- 취소된 것 제외
    </select>

    <!-- 세금계산서 발행 등록 -->
    <insert id="insert" parameterType="com.ga.core.vo.settle.TaxInvoiceVO"
            useGeneratedKeys="true" keyProperty="invoiceId">
        INSERT INTO tax_invoice (
            invoice_no, invoice_type, issue_date,
            supply_amount, tax_amount, total_amount,
            counterpart_name, counterpart_biz_no, counterpart_rep, counterpart_addr,
            agent_id, settle_month, settle_id,
            description, issued_by, created_at
        ) VALUES (
            #{invoiceNo}, #{invoiceType}, #{issueDate},
            #{supplyAmount}, #{taxAmount}, #{supplyAmount} + #{taxAmount},
            #{counterpartName}, #{counterpartBizNo}, #{counterpartRep}, #{counterpartAddr},
            #{agentId}, #{settleMonth}, #{settleId},
            #{description}, #{issuedBy}, NOW()
        )
    </insert>

    <!-- 세금계산서 취소 처리 -->
    <update id="cancel">
        UPDATE tax_invoice SET
            cancel_date   = #{cancelDate},
            cancel_reason = #{cancelReason},
            updated_at    = NOW()
        WHERE invoice_id  = #{invoiceId}
          AND cancel_date IS NULL  -- 이미 취소된 건은 재취소 불가
    </update>

</mapper>
