-- V1__create_tables.sql
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

-- Таблица организаций
CREATE TABLE organizations (
    uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    logo VARCHAR(255),
    title VARCHAR(255) NOT NULL,
    description TEXT,
    owner_uuid UUID,
    expires_at TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Таблица пользователей
CREATE TABLE app_users (
    uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    phone VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    first_name VARCHAR(100) NOT NULL,
    last_name VARCHAR(100) NOT NULL,
    role VARCHAR(50) NOT NULL,
    dating_profile_uuid UUID,
    balance INTEGER NOT NULL DEFAULT 0,
    enabled BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Таблица профилей знакомств
CREATE TABLE dating_profiles (
    uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Таблица расписаний
CREATE TABLE schedules (
    uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    day_of_week VARCHAR(20) NOT NULL,
    start_time TIME NOT NULL,
    end_time TIME NOT NULL
);

-- Таблица мест для знакомств
CREATE TABLE dating_places (
    uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    title VARCHAR(255) NOT NULL,
    photo VARCHAR(255),
    description TEXT,
    organization_uuid UUID REFERENCES organizations(uuid) ON DELETE SET NULL,
    dating_type VARCHAR(50) NOT NULL,
    price BIGINT NOT NULL DEFAULT 0,
    price_type VARCHAR(50) NOT NULL,
    dating_time VARCHAR(50) NOT NULL,
    start_time TIMESTAMP,
    duration BIGINT,
    schedule_uuids UUID[] DEFAULT '{}', -- МАССИВ UUID!
    location TEXT,
    coordinates VARCHAR(100),
    views INTEGER NOT NULL DEFAULT 0,
    in_favourite INTEGER NOT NULL DEFAULT 0,
    rating DOUBLE PRECISION,
    expiration_date TIMESTAMP,
    enabled BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Таблица планов знакомств
CREATE TABLE dating_plans (
    uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Таблица отзывов
CREATE TABLE feedbacks (
    uuid UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_uuid UUID REFERENCES app_users(uuid) ON DELETE CASCADE,
    dating_place_uuid UUID REFERENCES dating_places(uuid) ON DELETE CASCADE,
    feedback INTEGER NOT NULL CHECK (feedback >= 1 AND feedback <= 5),
    comment TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(user_uuid, dating_place_uuid)
);

-- Создаем функцию для обновления updated_at
CREATE OR REPLACE FUNCTION update_updated_at_column()
    RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ language 'plpgsql';

-- Создаем триггеры для всех таблиц
CREATE TRIGGER update_app_users_updated_at
    BEFORE UPDATE ON app_users
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_dating_places_updated_at
    BEFORE UPDATE ON dating_places
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_dating_plans_updated_at
    BEFORE UPDATE ON dating_plans
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_dating_profiles_updated_at
    BEFORE UPDATE ON dating_profiles
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_feedbacks_updated_at
    BEFORE UPDATE ON feedbacks
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_organizations_updated_at
    BEFORE UPDATE ON organizations
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Индексы для производительности
CREATE INDEX idx_app_users_phone ON app_users(phone);
CREATE INDEX idx_app_users_dating_profile_uuid ON app_users(dating_profile_uuid);
CREATE INDEX idx_dating_places_organization_uuid ON dating_places(organization_uuid);
CREATE INDEX idx_dating_places_dating_type ON dating_places(dating_type);
CREATE INDEX idx_dating_places_enabled ON dating_places(enabled);
CREATE INDEX idx_dating_places_expiration_date ON dating_places(expiration_date);
CREATE INDEX idx_feedbacks_user_uuid ON feedbacks(user_uuid);
CREATE INDEX idx_feedbacks_dating_place_uuid ON feedbacks(dating_place_uuid);
CREATE INDEX idx_organizations_owner_uuid ON organizations(owner_uuid);

-- Индекс для массива UUID (GIN индекс для операций с массивами)
CREATE INDEX idx_dating_places_schedule_uuids ON dating_places USING GIN(schedule_uuids);

-- Комментарии к таблицам
COMMENT ON TABLE organizations IS 'Организации, создающие места для свиданий';
COMMENT ON TABLE app_users IS 'Пользователи приложения';
COMMENT ON TABLE dating_profiles IS 'Профили пользователей для знакомств';
COMMENT ON TABLE schedules IS 'Расписание работы мест для свиданий';
COMMENT ON TABLE dating_places IS 'Места для свиданий';
COMMENT ON TABLE dating_plans IS 'Планы свиданий пользователей';
COMMENT ON TABLE feedbacks IS 'Отзывы о местах для свиданий';
COMMENT ON COLUMN dating_places.schedule_uuids IS 'Массив UUID расписаний для этого места';