-- Записи платежного календаря (расходы и поступления, по счету / без счета / наличка)
CREATE TABLE IF NOT EXISTS payment_calendar_entries (
  id                    BIGSERIAL PRIMARY KEY,
  direction             VARCHAR(20) NOT NULL CHECK (direction IN ('outgoing', 'incoming')),
  type                  VARCHAR(20) NOT NULL CHECK (type IN ('invoice', 'manual', 'cash')),
  payment_invoice_id    BIGINT REFERENCES payment_invoices(id) ON DELETE SET NULL,
  category              TEXT NOT NULL DEFAULT '',
  description           TEXT NOT NULL DEFAULT '',
  amount                NUMERIC(15, 2) NOT NULL,
  scheduled_date        DATE NOT NULL,
  payment_date          DATE,
  probability           VARCHAR(20) NOT NULL DEFAULT 'confirmed' CHECK (probability IN ('confirmed', 'high', 'medium', 'low')),
  currency              VARCHAR(10) NOT NULL DEFAULT 'RUB',
  is_cash               BOOLEAN NOT NULL DEFAULT FALSE,
  contractor_name       TEXT NOT NULL DEFAULT '',
  notes                 TEXT,
  created_by            TEXT NOT NULL,
  created_at            TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at            TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_payment_calendar_entries_direction ON payment_calendar_entries(direction);
CREATE INDEX IF NOT EXISTS idx_payment_calendar_entries_type ON payment_calendar_entries(type);
CREATE INDEX IF NOT EXISTS idx_payment_calendar_entries_scheduled_date ON payment_calendar_entries(scheduled_date);
CREATE INDEX IF NOT EXISTS idx_payment_calendar_entries_payment_date ON payment_calendar_entries(payment_date);
CREATE INDEX IF NOT EXISTS idx_payment_calendar_entries_payment_invoice_id ON payment_calendar_entries(payment_invoice_id);

COMMENT ON TABLE payment_calendar_entries IS 'Записи платежного календаря: расходы и поступления (по счету, без счета, наличка)';
