CREATE TABLE IF NOT EXISTS company_documents (
    id UUID PRIMARY KEY,
    company_id UUID NOT NULL REFERENCES companies(id),
    type TEXT NOT NULL, -- 'CNPJ', 'PERMIT', 'IDENTITY'
    url TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'PENDING', -- 'PENDING', 'APPROVED', 'REJECTED'
    rejection_reason TEXT,
    created_at TIMESTAMPTZ NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_company_documents_company_id ON company_documents (company_id);

CREATE TABLE IF NOT EXISTS ledger_entries (
    id UUID PRIMARY KEY,
    company_id UUID NOT NULL REFERENCES companies(id),
    amount_cents BIGINT NOT NULL, -- Positive for credit, Negative for debit
    type TEXT NOT NULL, -- 'SALE', 'FEE', 'WITHDRAWAL', 'REFUND'
    description TEXT NOT NULL,
    reference_id UUID, -- order_id or withdrawal_id
    created_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_ledger_entries_company_id ON ledger_entries (company_id);
CREATE INDEX IF NOT EXISTS idx_ledger_entries_created_at ON ledger_entries (created_at);

CREATE TABLE IF NOT EXISTS withdrawals (
    id UUID PRIMARY KEY,
    company_id UUID NOT NULL REFERENCES companies(id),
    amount_cents BIGINT NOT NULL,
    status TEXT NOT NULL DEFAULT 'PENDING', -- 'PENDING', 'APPROVED', 'PAID', 'REJECTED'
    bank_account_info TEXT NOT NULL, -- JSON or text description
    transaction_id TEXT, -- Bank transaction ID if paid
    rejection_reason TEXT,
    created_at TIMESTAMPTZ NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_withdrawals_company_id ON withdrawals (company_id);
