-- V2__create_tables.sql

-- Расширение для генерации UUID
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

-- Функция для автоматического обновления поля updated_at
CREATE OR REPLACE FUNCTION update_updated_at_column()
    RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ language 'plpgsql';

-- =====================================================
-- Таблица app_users
-- =====================================================
CREATE TABLE app_users (
                           uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                           phone TEXT NOT NULL UNIQUE,
                           password TEXT,
                           last_name TEXT NOT NULL,
                           first_name TEXT NOT NULL,
                           role TEXT NOT NULL DEFAULT 'USER',
                           enabled BOOLEAN NOT NULL DEFAULT TRUE,
                           created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                           updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

COMMENT ON TABLE app_users IS 'Пользователи приложения';
COMMENT ON COLUMN app_users.role IS 'Роль пользователя: USER, ADMIN, MODERATOR';
COMMENT ON COLUMN app_users.enabled IS 'Активен ли аккаунт';

-- =====================================================
-- Таблица tennis_clubs
-- =====================================================
CREATE TABLE tennis_clubs (
                              uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                              name TEXT NOT NULL,
                              description TEXT,
                              address TEXT,
                              phone TEXT,
                              email TEXT,
                              website TEXT,
                              images TEXT[] DEFAULT '{}',
                              court_uuids UUID[] DEFAULT '{}',
                              conveniences TEXT,
                              owner_uuid UUID,
                              created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                              updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

COMMENT ON TABLE tennis_clubs IS 'Теннисные клубы';
COMMENT ON COLUMN tennis_clubs.images IS 'Массив ссылок на изображения клуба';
COMMENT ON COLUMN tennis_clubs.court_uuids IS 'Массив UUID кортов, принадлежащих клубу';
COMMENT ON COLUMN tennis_clubs.conveniences IS 'Удобства клуба (раздевалки, душ, кафе и т.д.)';

-- =====================================================
-- Таблица courts
-- =====================================================
CREATE TABLE courts (
                        uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                        name TEXT NOT NULL,
                        photo TEXT,
                        price INTEGER NOT NULL,
                        cover TEXT,
                        is_outdoor BOOLEAN NOT NULL DEFAULT FALSE,
                        is_visible BOOLEAN NOT NULL DEFAULT TRUE,
                        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                        updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

COMMENT ON TABLE courts IS 'Теннисные корты';
COMMENT ON COLUMN courts.price IS 'Цена за час аренды в рублях';
COMMENT ON COLUMN courts.cover IS 'Тип покрытия (грунт, хард, трава)';
COMMENT ON COLUMN courts.is_outdoor IS 'Открытый корт (true) или крытый (false)';
COMMENT ON COLUMN courts.is_visible IS 'Виден ли корт для бронирования';

-- =====================================================
-- Таблица tennis_events
-- =====================================================
CREATE TABLE tennis_events (
                               uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
                               club_uuid UUID NOT NULL,
                               title TEXT NOT NULL,
                               description TEXT,
                               type TEXT NOT NULL,
                               start_datetime TIMESTAMP NOT NULL,
                               end_datetime TIMESTAMP,
                               max_participants INTEGER,
                               current_participants INTEGER NOT NULL DEFAULT 0,
                               take_part_price DECIMAL(10, 2),
                               rewards TEXT,
                               requirements TEXT,
                               contact_email TEXT,
                               contact_phone TEXT,
                               image_url TEXT,
                               created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                               updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

    -- Внешний ключ
                               CONSTRAINT fk_tennis_events_club FOREIGN KEY (club_uuid)
                                   REFERENCES tennis_clubs(uuid) ON DELETE CASCADE
);

COMMENT ON TABLE tennis_events IS 'Теннисные мероприятия (тренировки, турниры, игры)';
COMMENT ON COLUMN tennis_events.type IS 'Тип мероприятия: TRAINING, TOURNAMENT, FRIENDLY_MATCH, MASTER_CLASS, OPEN_COURT';
COMMENT ON COLUMN tennis_events.max_participants IS 'Максимальное количество участников';
COMMENT ON COLUMN tennis_events.current_participants IS 'Текущее количество участников';
COMMENT ON COLUMN tennis_events.take_part_price IS 'Цена участия';
COMMENT ON COLUMN tennis_events.rewards IS 'Призы и награды';
COMMENT ON COLUMN tennis_events.requirements IS 'Требования к участникам (уровень игры, экипировка и т.д.)';

-- =====================================================
-- Триггеры для обновления updated_at
-- =====================================================
CREATE TRIGGER update_app_users_updated_at
    BEFORE UPDATE ON app_users
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_tennis_clubs_updated_at
    BEFORE UPDATE ON tennis_clubs
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_courts_updated_at
    BEFORE UPDATE ON courts
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_tennis_events_updated_at
    BEFORE UPDATE ON tennis_events
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- =====================================================
-- Индексы для производительности
-- =====================================================

-- Индексы для app_users
CREATE INDEX idx_app_users_phone ON app_users(phone);
CREATE INDEX idx_app_users_role ON app_users(role);
CREATE INDEX idx_app_users_enabled ON app_users(enabled);

-- Индексы для tennis_clubs
CREATE INDEX idx_tennis_clubs_name ON tennis_clubs(name);
CREATE INDEX idx_tennis_clubs_address ON tennis_clubs(address);
CREATE INDEX idx_tennis_clubs_email ON tennis_clubs(email);
CREATE INDEX idx_tennis_clubs_phone ON tennis_clubs(phone);

-- GIN индекс для поиска по массиву изображений
CREATE INDEX idx_tennis_clubs_images ON tennis_clubs USING GIN (images);

-- GIN индекс для поиска по массиву UUID кортов
CREATE INDEX idx_tennis_clubs_court_uuids ON tennis_clubs USING GIN (court_uuids);

-- Индексы для courts
CREATE INDEX idx_courts_name ON courts(name);
CREATE INDEX idx_courts_price ON courts(price);
CREATE INDEX idx_courts_cover ON courts(cover);
CREATE INDEX idx_courts_is_outdoor ON courts(is_outdoor);
CREATE INDEX idx_courts_is_visible ON courts(is_visible);

-- Индексы для tennis_events
CREATE INDEX idx_tennis_events_club_uuid ON tennis_events(club_uuid);
CREATE INDEX idx_tennis_events_type ON tennis_events(type);
CREATE INDEX idx_tennis_events_start_datetime ON tennis_events(start_datetime);
CREATE INDEX idx_tennis_events_club_status ON tennis_events(club_uuid, start_datetime);
CREATE INDEX idx_tennis_events_start_end ON tennis_events(start_datetime, end_datetime);

-- =====================================================
-- Комментарии к таблицам
-- =====================================================
COMMENT ON TABLE app_users IS 'Пользователи приложения';
COMMENT ON TABLE tennis_clubs IS 'Теннисные клубы';
COMMENT ON TABLE courts IS 'Теннисные корты';
COMMENT ON TABLE tennis_events IS 'Теннисные мероприятия';