-- Migration: 006_JournalEntryDrafts
-- Description: Create journal entry draft read models table for kassekladde feature

CREATE TABLE IF NOT EXISTS journal_entry_draft_read_models (
    aggregate_id TEXT PRIMARY KEY,
    company_id TEXT NOT NULL,
    name TEXT NOT NULL,
    date DATE,
    description TEXT,
    fiscal_year_id TEXT,
    lines TEXT NOT NULL DEFAULT '[]',
    status TEXT NOT NULL DEFAULT 'active',
    transaction_id TEXT,
    created_by TEXT NOT NULL,
    create_time TIMESTAMPTZ NOT NULL,
    updated_time TIMESTAMPTZ NOT NULL,
    last_aggregate_sequence_number INT NOT NULL
);

-- Index for efficient queries by company and status
CREATE INDEX IF NOT EXISTS idx_journal_entry_draft_company_status
    ON journal_entry_draft_read_models(company_id, status);

-- Index for efficient queries by company ordered by updated time
CREATE INDEX IF NOT EXISTS idx_journal_entry_draft_company_updated
    ON journal_entry_draft_read_models(company_id, updated_time DESC);

COMMENT ON TABLE journal_entry_draft_read_models IS 'Journal entry drafts (kassekladder) - work in progress entries before posting to ledger';
COMMENT ON COLUMN journal_entry_draft_read_models.status IS 'active = work in progress, posted = sent to ledger, discarded = deleted';
COMMENT ON COLUMN journal_entry_draft_read_models.lines IS 'JSON array (stored as TEXT) of draft lines with accountId, debitAmount, creditAmount, description';
