-- Migration: 048_board_documents.sql
-- Date: 2026-02-03
-- Description: Board documents table for Rada Izby (protocols, minutes, resolutions)
-- Author: Claude Code

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

    -- Document metadata
    title VARCHAR(255) NOT NULL,
    description TEXT,
    document_type VARCHAR(50) DEFAULT 'protocol',

    -- Meeting reference
    meeting_date DATE NOT NULL,
    meeting_number INTEGER,

    -- File metadata
    original_filename VARCHAR(255) NOT NULL,
    stored_filename VARCHAR(255) NOT NULL UNIQUE,
    file_extension VARCHAR(10) NOT NULL,
    file_size INTEGER NOT NULL,
    mime_type VARCHAR(100) NOT NULL,

    -- Upload tracking
    uploaded_by INTEGER NOT NULL REFERENCES users(id),
    uploaded_at TIMESTAMP DEFAULT NOW(),

    -- Audit fields
    updated_at TIMESTAMP,
    updated_by INTEGER REFERENCES users(id),
    is_active BOOLEAN DEFAULT TRUE
);

-- Indexes for common queries
CREATE INDEX IF NOT EXISTS idx_board_documents_meeting_date ON board_documents(meeting_date);
CREATE INDEX IF NOT EXISTS idx_board_documents_document_type ON board_documents(document_type);
CREATE INDEX IF NOT EXISTS idx_board_documents_is_active ON board_documents(is_active);

-- Grant permissions to application user
GRANT ALL ON TABLE board_documents TO nordabiz_app;
GRANT USAGE, SELECT ON SEQUENCE board_documents_id_seq TO nordabiz_app;

-- Set is_rada_member for known board members
-- Note: Only updates users that exist in the database
UPDATE users SET is_rada_member = TRUE
WHERE email IN (
    'leszek@rotor.pl',
    'artur.wiertel@norda-biznes.info',
    'pawel.kwidzinski@norda-biznes.info',
    'jm@hebel-masiak.pl',
    'iwonamusial@cristap.pl',
    'andrzej.gorczycki@zukwejherowo.pl',
    'dariusz.schmidtke@tkchopin.pl',
    'a.jedrzejewski@scrol.pl',
    'krzysztof.kubis@sibuk.pl',
    'info@greenhousesystems.pl',
    'kuba@bormax.com.pl',
    'pawel.piechota@norda-biznes.info',
    'jacek.pomieczynski@eura-tech.eu',
    'radoslaw@skwarlo.pl',
    'roman@sigmabudownictwo.pl',
    'mjwesierski@gmail.com'
);

-- Log how many users were updated
DO $$
DECLARE
    updated_count INTEGER;
BEGIN
    SELECT COUNT(*) INTO updated_count FROM users WHERE is_rada_member = TRUE;
    RAISE NOTICE 'Board members set: % users have is_rada_member = TRUE', updated_count;
END $$;
