-- Migration: 018_InvoiceTypeConsolidation.sql
-- Description: Consolidate credit notes into invoice table with type discrimination
-- Date: 2026-01-19
-- Breaking change: Credit notes become invoices with type='credit_note'

-- Add invoice type discrimination column
ALTER TABLE invoice_read_models
ADD COLUMN IF NOT EXISTS invoice_type VARCHAR(20) NOT NULL DEFAULT 'invoice';

-- Add credit note specific columns
ALTER TABLE invoice_read_models
ADD COLUMN IF NOT EXISTS original_invoice_id VARCHAR(255),
ADD COLUMN IF NOT EXISTS original_invoice_number VARCHAR(50),
ADD COLUMN IF NOT EXISTS credit_reason TEXT,
ADD COLUMN IF NOT EXISTS amount_applied DECIMAL(18, 2) NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS issued_at TIMESTAMP WITH TIME ZONE;

-- Create index for invoice type filtering
CREATE INDEX IF NOT EXISTS idx_invoice_type ON invoice_read_models(invoice_type);

-- Create index for credit note -> original invoice lookup
CREATE INDEX IF NOT EXISTS idx_invoice_original_invoice ON invoice_read_models(original_invoice_id)
    WHERE original_invoice_id IS NOT NULL;

-- Migrate existing credit notes to invoice table
-- Note: This assumes credit_note_read_models table exists
DO $$
BEGIN
    IF EXISTS (
        SELECT FROM information_schema.tables
        WHERE table_name = 'credit_note_read_models'
    ) THEN
        -- Insert credit notes as invoices with type='credit_note'
        INSERT INTO invoice_read_models (
            aggregate_id,
            last_aggregate_sequence_number,
            create_time,
            update_time,
            company_id,
            fiscal_year_id,
            customer_id,
            customer_name,
            customer_number,
            invoice_number,  -- Using credit_note_number
            invoice_date,    -- Using credit_note_date
            due_date,        -- Same as invoice_date for credit notes
            status,
            amount_ex_vat,
            amount_vat,
            amount_total,
            amount_paid,
            amount_remaining,
            currency,
            vat_code,
            payment_terms_days,
            lines,
            ledger_transaction_id,
            notes,
            reference,
            sent_at,
            voided_at,
            voided_reason,
            created_by,
            -- New credit note specific columns
            invoice_type,
            original_invoice_id,
            original_invoice_number,
            credit_reason,
            amount_applied,
            issued_at
        )
        SELECT
            aggregate_id,
            last_aggregate_sequence_number,
            create_time,
            update_time,
            company_id,
            fiscal_year_id,
            customer_id,
            customer_name,
            '', -- customer_number not in credit notes, will need to be populated
            credit_note_number,
            credit_note_date,
            credit_note_date, -- due_date = issue date for credit notes
            -- Map credit note status to invoice status
            CASE status
                WHEN 'Draft' THEN 'draft'
                WHEN 'Issued' THEN 'issued'
                WHEN 'PartiallyApplied' THEN 'partially_applied'
                WHEN 'FullyApplied' THEN 'fully_applied'
                WHEN 'Voided' THEN 'voided'
                ELSE LOWER(status)
            END,
            -- Amounts are negative for credit notes
            -ABS(amount_ex_vat),
            -ABS(amount_vat),
            -ABS(amount_total),
            0, -- amount_paid (credit notes use amount_applied instead)
            -ABS(amount_remaining),
            'DKK', -- Default currency
            NULL, -- vat_code
            0, -- payment_terms_days
            lines,
            ledger_transaction_id,
            reason, -- notes = reason
            NULL, -- reference
            issued_at, -- sent_at = issued_at for credit notes
            voided_at,
            voided_reason,
            'system', -- created_by (not tracked in old model)
            -- Credit note specific
            'credit_note',
            original_invoice_id,
            original_invoice_number,
            reason,
            amount_applied,
            issued_at
        FROM credit_note_read_models
        ON CONFLICT (aggregate_id) DO NOTHING;

        RAISE NOTICE 'Migrated credit notes to invoice table';
    END IF;
END $$;

-- Update credit_note_applications to reference invoice table
-- (keeping for historical reference, can be dropped after verification)
COMMENT ON TABLE credit_note_applications IS 'DEPRECATED: Credit note applications are now tracked via invoice events. Table kept for migration reference.';

-- Drop credit note read models table after successful migration
-- Uncomment these after verifying migration success:
-- DROP TABLE IF EXISTS credit_note_applications;
-- DROP TABLE IF EXISTS credit_note_read_models;

-- Add comment explaining the consolidation
COMMENT ON COLUMN invoice_read_models.invoice_type IS 'Document type: invoice or credit_note';
COMMENT ON COLUMN invoice_read_models.original_invoice_id IS 'For credit notes: reference to the original invoice being credited';
COMMENT ON COLUMN invoice_read_models.original_invoice_number IS 'For credit notes: the invoice number of the original invoice';
COMMENT ON COLUMN invoice_read_models.credit_reason IS 'For credit notes: reason for issuing the credit';
COMMENT ON COLUMN invoice_read_models.amount_applied IS 'For credit notes: total credit amount applied to invoices';
COMMENT ON COLUMN invoice_read_models.issued_at IS 'For credit notes: when the credit note was issued (equivalent to sent_at for invoices)';
