-- Migration: Board Meetings (Agenda & Protocol Forms)
-- Date: 2026-02-03
-- Description: Creates table for structured board meeting data (agenda, attendance, proceedings)

-- Create board_meetings table
CREATE TABLE IF NOT EXISTS board_meetings (
    id SERIAL PRIMARY KEY,

    -- Meeting identification
    meeting_number INTEGER NOT NULL,
    year INTEGER NOT NULL,

    -- Meeting schedule
    meeting_date DATE NOT NULL,
    start_time TIME,
    end_time TIME,
    location VARCHAR(255) DEFAULT 'Siedziba Izby',

    -- Meeting roles
    chairperson_id INTEGER REFERENCES users(id),
    secretary_id INTEGER REFERENCES users(id),

    -- Guests (non-members)
    guests TEXT,

    -- Structured data (JSON)
    agenda_items JSONB,
    attendance JSONB,
    proceedings JSONB,

    -- Quorum
    quorum_count INTEGER,
    quorum_confirmed BOOLEAN,

    -- Status workflow: draft -> agenda_published -> protocol_draft -> protocol_published
    status VARCHAR(20) DEFAULT 'draft',

    -- Audit fields
    created_by INTEGER NOT NULL REFERENCES users(id),
    created_at TIMESTAMP DEFAULT NOW(),
    updated_by INTEGER REFERENCES users(id),
    updated_at TIMESTAMP,
    agenda_published_at TIMESTAMP,
    protocol_published_at TIMESTAMP,

    -- Unique constraint for meeting number per year
    CONSTRAINT uq_board_meeting_number_year UNIQUE (meeting_number, year)
);

-- Indexes
CREATE INDEX idx_board_meetings_year ON board_meetings(year);
CREATE INDEX idx_board_meetings_date ON board_meetings(meeting_date);
CREATE INDEX idx_board_meetings_status ON board_meetings(status);

-- Grant permissions
GRANT ALL ON TABLE board_meetings TO nordabiz_app;
GRANT USAGE, SELECT ON SEQUENCE board_meetings_id_seq TO nordabiz_app;

-- Add comment
COMMENT ON TABLE board_meetings IS 'Stores structured board meeting data including agenda, attendance, and proceedings';
