-- =====================================================
-- ARQUITETURA COMPLETA DE TESOURO - NOVAS TABELAS
-- Similar à arquitetura de Elaboração e Aprovação do Orçamento
-- =====================================================

-- Contas de Caixa/Bancárias
CREATE TABLE IF NOT EXISTS public.cash_account (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    code VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(200) NOT NULL,
    type VARCHAR(20) NOT NULL, -- CASH, BANK_ACCOUNT
    bank_id UUID,
    account_number VARCHAR(50),
    branch_code VARCHAR(20),
    currency VARCHAR(3) DEFAULT 'XOF',
    is_active BOOLEAN DEFAULT true,
    current_balance NUMERIC(19,2) DEFAULT 0,
    available_balance NUMERIC(19,2) DEFAULT 0,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    version BIGINT DEFAULT 0
);

CREATE INDEX idx_cash_account_code ON public.cash_account(code);
CREATE INDEX idx_cash_account_type ON public.cash_account(type);
CREATE INDEX idx_cash_account_active ON public.cash_account(is_active);

-- Entradas de Tesouraria (Similar a budget_entry)
CREATE TABLE IF NOT EXISTS public.treasury_entry (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    cash_account_id UUID NOT NULL REFERENCES public.cash_account(id),
    type VARCHAR(50) NOT NULL,
    amount NUMERIC(19,2) NOT NULL,
    transaction_date DATE NOT NULL,
    document_reference VARCHAR(100),
    description TEXT,
    status VARCHAR(20) NOT NULL DEFAULT 'DRAFT', -- DRAFT, PENDING_APPROVAL, APPROVED, REJECTED, EXECUTED
    approval_level INTEGER,
    approved_by UUID,
    approved_at TIMESTAMP,
    payment_order_id UUID,
    payment_batch_id UUID,
    budget_line_id UUID,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    version BIGINT DEFAULT 0
);

CREATE INDEX idx_treasury_entry_cash_account ON public.treasury_entry(cash_account_id);
CREATE INDEX idx_treasury_entry_type ON public.treasury_entry(type);
CREATE INDEX idx_treasury_entry_status ON public.treasury_entry(status);
CREATE INDEX idx_treasury_entry_date ON public.treasury_entry(transaction_date);
CREATE INDEX idx_treasury_entry_payment_order ON public.treasury_entry(payment_order_id);

-- Autorizações de Pagamento
CREATE TABLE IF NOT EXISTS public.payment_authorization (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    payment_order_id UUID,
    payment_batch_id UUID,
    requested_by UUID NOT NULL,
    requested_at TIMESTAMP NOT NULL,
    required_approval_level INTEGER NOT NULL,
    current_approval_level INTEGER DEFAULT 1,
    status VARCHAR(20) NOT NULL DEFAULT 'PENDING', -- PENDING, PARTIALLY_APPROVED, APPROVED, REJECTED
    rejection_reason TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    version BIGINT DEFAULT 0
);

CREATE INDEX idx_auth_payment_order ON public.payment_authorization(payment_order_id);
CREATE INDEX idx_auth_payment_batch ON public.payment_authorization(payment_batch_id);
CREATE INDEX idx_auth_status ON public.payment_authorization(status);
CREATE INDEX idx_auth_requested_by ON public.payment_authorization(requested_by);

-- Aprovações (Histórico)
CREATE TABLE IF NOT EXISTS public.approval (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    authorization_id UUID NOT NULL REFERENCES public.payment_authorization(id),
    level INTEGER NOT NULL,
    approved_by UUID NOT NULL,
    approved_at TIMESTAMP NOT NULL,
    comments TEXT,
    signature_hash VARCHAR(255)
);

CREATE INDEX idx_approval_authorization ON public.approval(authorization_id);
CREATE INDEX idx_approval_approver ON public.approval(approved_by);
CREATE INDEX idx_approval_level ON public.approval(level);

-- Fluxo de Caixa
CREATE TABLE IF NOT EXISTS public.cash_flow (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    cash_account_id UUID NOT NULL REFERENCES public.cash_account(id),
    transaction_date DATE NOT NULL,
    type VARCHAR(20) NOT NULL, -- INFLOW, OUTFLOW
    amount NUMERIC(19,2) NOT NULL,
    description TEXT,
    reference_id UUID,
    reference_type VARCHAR(50),
    balance_after NUMERIC(19,2) NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    version BIGINT DEFAULT 0
);

CREATE INDEX idx_cash_flow_account ON public.cash_flow(cash_account_id);
CREATE INDEX idx_cash_flow_date ON public.cash_flow(transaction_date);
CREATE INDEX idx_cash_flow_type ON public.cash_flow(type);
CREATE INDEX idx_cash_flow_reference ON public.cash_flow(reference_type, reference_id);

-- Conciliação Bancária
CREATE TABLE IF NOT EXISTS public.bank_reconciliation (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    cash_account_id UUID NOT NULL REFERENCES public.cash_account(id),
    reconciliation_date DATE NOT NULL,
    statement_balance NUMERIC(19,2) NOT NULL,
    system_balance NUMERIC(19,2) NOT NULL,
    difference NUMERIC(19,2),
    status VARCHAR(20) NOT NULL DEFAULT 'PENDING', -- PENDING, RECONCILED, DISCREPANCY
    reconciled_by UUID,
    reconciled_at TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    version BIGINT DEFAULT 0
);

CREATE INDEX idx_reconciliation_cash_account ON public.bank_reconciliation(cash_account_id);
CREATE INDEX idx_reconciliation_date ON public.bank_reconciliation(reconciliation_date);
CREATE INDEX idx_reconciliation_status ON public.bank_reconciliation(status);

-- Itens de Conciliação
CREATE TABLE IF NOT EXISTS public.reconciliation_item (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    reconciliation_id UUID NOT NULL REFERENCES public.bank_reconciliation(id),
    transaction_date DATE NOT NULL,
    description TEXT,
    statement_amount NUMERIC(19,2),
    system_amount NUMERIC(19,2),
    match_status VARCHAR(20) NOT NULL DEFAULT 'PENDING', -- MATCHED, UNMATCHED, PENDING
    matched_transaction_id UUID,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_reconciliation_item_reconciliation ON public.reconciliation_item(reconciliation_id);
CREATE INDEX idx_reconciliation_item_status ON public.reconciliation_item(match_status);
CREATE INDEX idx_reconciliation_item_date ON public.reconciliation_item(transaction_date);

-- Comentários
COMMENT ON TABLE public.cash_account IS 'Contas de caixa e bancárias do Tesouro';
COMMENT ON TABLE public.treasury_entry IS 'Entradas de tesouraria - rastreamento completo do ciclo de vida';
COMMENT ON TABLE public.payment_authorization IS 'Workflow de aprovação hierárquica de pagamentos';
COMMENT ON TABLE public.approval IS 'Histórico de aprovações individuais';
COMMENT ON TABLE public.cash_flow IS 'Fluxo de caixa - entradas e saídas';
COMMENT ON TABLE public.bank_reconciliation IS 'Conciliação bancária';
COMMENT ON TABLE public.reconciliation_item IS 'Itens de conciliação bancária';

