BEGIN;

CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$;

-- PostgreSQL 10-compatible UUID generator without an extension dependency.
CREATE OR REPLACE FUNCTION generate_uuid_v4()
RETURNS uuid
LANGUAGE sql
VOLATILE
AS $$
  SELECT (
    substr(base, 1, 8) || '-' ||
    substr(base, 9, 4) || '-' ||
    '4' || substr(base, 14, 3) || '-' ||
    substr('89ab', floor(random() * 4)::int + 1, 1) || substr(base, 18, 3) || '-' ||
    substr(base, 21, 12)
  )::uuid
  FROM (
    SELECT md5(random()::text || clock_timestamp()::text || random()::text) AS base
  ) AS seed;
$$;

CREATE OR REPLACE FUNCTION set_properties_search_vector()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  NEW.search_vector := to_tsvector(
    'simple'::regconfig,
    coalesce(NEW.title, '') || ' ' ||
    coalesce(NEW.short_title, '') || ' ' ||
    coalesce(NEW.description, '') || ' ' ||
    coalesce(NEW.address_text, '')
  );
  RETURN NEW;
END;
$$;

CREATE OR REPLACE FUNCTION set_pages_search_vector()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  NEW.search_vector := to_tsvector(
    'simple'::regconfig,
    coalesce(NEW.title, '') || ' ' ||
    coalesce(NEW.excerpt, '') || ' ' ||
    coalesce(NEW.content, '')
  );
  RETURN NEW;
END;
$$;

CREATE OR REPLACE FUNCTION set_blog_posts_search_vector()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  NEW.search_vector := to_tsvector(
    'simple'::regconfig,
    coalesce(NEW.title, '') || ' ' ||
    coalesce(NEW.excerpt, '') || ' ' ||
    coalesce(NEW.content, '')
  );
  RETURN NEW;
END;
$$;

CREATE TABLE admin_users (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  email text NOT NULL,
  full_name text NOT NULL,
  role_code text NOT NULL CHECK (role_code IN ('super_admin', 'admin', 'editor', 'broker', 'support')),
  password_hash text,
  is_active boolean NOT NULL DEFAULT true,
  last_login_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  deleted_at timestamptz,
  CONSTRAINT uq_admin_users_email UNIQUE (email)
);

CREATE TABLE currencies (
  code varchar(3) PRIMARY KEY,
  name text NOT NULL,
  symbol text NOT NULL,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT chk_currencies_code_upper CHECK (code = UPPER(code))
);

CREATE TABLE property_types (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  code text NOT NULL,
  name text NOT NULL,
  slug text NOT NULL,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_property_types_code UNIQUE (code),
  CONSTRAINT uq_property_types_slug UNIQUE (slug)
);

CREATE TABLE deal_types (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  code text NOT NULL,
  name text NOT NULL,
  slug text NOT NULL,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_deal_types_code UNIQUE (code),
  CONSTRAINT uq_deal_types_slug UNIQUE (slug)
);

CREATE TABLE property_statuses (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  code text NOT NULL,
  name text NOT NULL,
  is_public boolean NOT NULL DEFAULT true,
  sort_order integer NOT NULL DEFAULT 0,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_property_statuses_code UNIQUE (code)
);

CREATE TABLE location_types (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  code text NOT NULL,
  name text NOT NULL,
  sort_order integer NOT NULL DEFAULT 0,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_location_types_code UNIQUE (code)
);

CREATE TABLE media_types (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  code text NOT NULL,
  name text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_media_types_code UNIQUE (code)
);

CREATE TABLE inquiry_types (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  code text NOT NULL,
  name text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_inquiry_types_code UNIQUE (code)
);

CREATE TABLE inquiry_statuses (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  code text NOT NULL,
  name text NOT NULL,
  is_terminal boolean NOT NULL DEFAULT false,
  sort_order integer NOT NULL DEFAULT 0,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_inquiry_statuses_code UNIQUE (code)
);

CREATE TABLE page_types (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  code text NOT NULL,
  name text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_page_types_code UNIQUE (code)
);

CREATE TABLE locations (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  parent_id uuid REFERENCES locations(id) ON DELETE RESTRICT,
  location_type_id uuid NOT NULL REFERENCES location_types(id) ON DELETE RESTRICT,
  country_code char(2) NOT NULL DEFAULT 'GR',
  name text NOT NULL,
  slug text NOT NULL,
  latitude numeric(9,6),
  longitude numeric(9,6),
  sort_order integer NOT NULL DEFAULT 0,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT chk_locations_country_code_upper CHECK (country_code = UPPER(country_code))
);

CREATE UNIQUE INDEX uq_locations_parent_slug
  ON locations(parent_id, slug)
  WHERE parent_id IS NOT NULL;

CREATE UNIQUE INDEX uq_locations_root_slug
  ON locations(slug)
  WHERE parent_id IS NULL;

CREATE TABLE offices (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  location_id uuid REFERENCES locations(id) ON DELETE SET NULL,
  name text NOT NULL,
  slug text NOT NULL,
  email text NOT NULL,
  phone text,
  address text NOT NULL,
  city text,
  region text,
  latitude numeric(9,6),
  longitude numeric(9,6),
  working_hours text,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_offices_slug UNIQUE (slug)
);

CREATE TABLE properties (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  ref_number text NOT NULL,
  slug text NOT NULL,
  title text NOT NULL,
  short_title text,
  description text NOT NULL,
  property_type_id uuid NOT NULL REFERENCES property_types(id) ON DELETE RESTRICT,
  deal_type_id uuid NOT NULL REFERENCES deal_types(id) ON DELETE RESTRICT,
  status_id uuid NOT NULL REFERENCES property_statuses(id) ON DELETE RESTRICT,
  office_id uuid NOT NULL REFERENCES offices(id) ON DELETE RESTRICT,
  location_id uuid NOT NULL REFERENCES locations(id) ON DELETE RESTRICT,
  price numeric(14,2),
  currency_code varchar(3) NOT NULL REFERENCES currencies(code) ON DELETE RESTRICT,
  area_total numeric(12,2),
  area_built numeric(12,2),
  area_plot numeric(12,2),
  bedrooms_count smallint,
  bathrooms_count smallint,
  floor_number smallint,
  floors_total smallint,
  year_built integer,
  latitude numeric(9,6),
  longitude numeric(9,6),
  address_text text,
  is_featured boolean NOT NULL DEFAULT false,
  is_new_build boolean NOT NULL DEFAULT false,
  is_luxury boolean NOT NULL DEFAULT false,
  is_active boolean NOT NULL DEFAULT false,
  published_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  deleted_at timestamptz,
  search_vector tsvector,
  CONSTRAINT uq_properties_ref_number UNIQUE (ref_number),
  CONSTRAINT uq_properties_slug UNIQUE (slug),
  CONSTRAINT chk_properties_price_nonnegative CHECK (price IS NULL OR price >= 0),
  CONSTRAINT chk_properties_area_total_nonnegative CHECK (area_total IS NULL OR area_total >= 0),
  CONSTRAINT chk_properties_area_built_nonnegative CHECK (area_built IS NULL OR area_built >= 0),
  CONSTRAINT chk_properties_area_plot_nonnegative CHECK (area_plot IS NULL OR area_plot >= 0),
  CONSTRAINT chk_properties_bedrooms_nonnegative CHECK (bedrooms_count IS NULL OR bedrooms_count >= 0),
  CONSTRAINT chk_properties_bathrooms_nonnegative CHECK (bathrooms_count IS NULL OR bathrooms_count >= 0),
  CONSTRAINT chk_properties_year_built_reasonable CHECK (year_built IS NULL OR year_built BETWEEN 1800 AND 2100)
);

CREATE TABLE property_media (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  property_id uuid NOT NULL REFERENCES properties(id) ON DELETE CASCADE,
  media_type_id uuid NOT NULL REFERENCES media_types(id) ON DELETE RESTRICT,
  file_url text NOT NULL,
  alt_text text,
  title text,
  sort_order integer NOT NULL DEFAULT 0,
  is_cover boolean NOT NULL DEFAULT false,
  created_at timestamptz NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX uq_property_media_cover_per_property
  ON property_media(property_id)
  WHERE is_cover = true;

CREATE TABLE inquiries (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  inquiry_type_id uuid NOT NULL REFERENCES inquiry_types(id) ON DELETE RESTRICT,
  property_id uuid REFERENCES properties(id) ON DELETE SET NULL,
  office_id uuid REFERENCES offices(id) ON DELETE SET NULL,
  full_name text NOT NULL,
  email text NOT NULL,
  phone text,
  message text,
  source text,
  source_url text,
  status_id uuid NOT NULL REFERENCES inquiry_statuses(id) ON DELETE RESTRICT,
  assigned_to_user_id uuid REFERENCES admin_users(id) ON DELETE SET NULL,
  ip_address inet,
  user_agent text,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  deleted_at timestamptz
);

CREATE TABLE inquiry_logs (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  inquiry_id uuid NOT NULL REFERENCES inquiries(id) ON DELETE CASCADE,
  changed_by_user_id uuid REFERENCES admin_users(id) ON DELETE SET NULL,
  old_status_id uuid REFERENCES inquiry_statuses(id) ON DELETE SET NULL,
  new_status_id uuid REFERENCES inquiry_statuses(id) ON DELETE SET NULL,
  note text,
  old_value_json jsonb,
  new_value_json jsonb,
  created_at timestamptz NOT NULL DEFAULT NOW()
);

CREATE TABLE custom_field_groups (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  property_type_id uuid NOT NULL REFERENCES property_types(id) ON DELETE CASCADE,
  name text NOT NULL,
  code text NOT NULL,
  sort_order integer NOT NULL DEFAULT 0,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_custom_field_groups_type_code UNIQUE (property_type_id, code)
);

CREATE TABLE custom_field_definitions (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  property_type_id uuid NOT NULL REFERENCES property_types(id) ON DELETE CASCADE,
  group_id uuid REFERENCES custom_field_groups(id) ON DELETE SET NULL,
  code text NOT NULL,
  label text NOT NULL,
  field_type text NOT NULL CHECK (field_type IN ('text', 'number', 'textarea', 'select', 'multiselect', 'checkbox', 'radio', 'boolean', 'date')),
  placeholder text,
  help_text text,
  is_required boolean NOT NULL DEFAULT false,
  is_filterable boolean NOT NULL DEFAULT false,
  is_visible_in_listing boolean NOT NULL DEFAULT false,
  is_visible_in_detail boolean NOT NULL DEFAULT true,
  default_value text,
  sort_order integer NOT NULL DEFAULT 0,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_custom_field_definitions_type_code UNIQUE (property_type_id, code)
);

CREATE TABLE custom_field_options (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  field_definition_id uuid NOT NULL REFERENCES custom_field_definitions(id) ON DELETE CASCADE,
  value_code text NOT NULL,
  value_label text NOT NULL,
  sort_order integer NOT NULL DEFAULT 0,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_custom_field_options_field_value UNIQUE (field_definition_id, value_code)
);

CREATE TABLE property_custom_field_values (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  property_id uuid NOT NULL REFERENCES properties(id) ON DELETE CASCADE,
  field_definition_id uuid NOT NULL REFERENCES custom_field_definitions(id) ON DELETE CASCADE,
  value_text text,
  value_number numeric(14,2),
  value_boolean boolean,
  value_date date,
  value_option_id uuid REFERENCES custom_field_options(id) ON DELETE SET NULL,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_property_custom_field_values UNIQUE (property_id, field_definition_id),
  CONSTRAINT chk_property_custom_field_values_single_value CHECK (
    num_nonnulls(value_text, value_number, value_boolean, value_date, value_option_id) = 1
  )
);

CREATE TABLE property_custom_field_multi_values (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  property_id uuid NOT NULL REFERENCES properties(id) ON DELETE CASCADE,
  field_definition_id uuid NOT NULL REFERENCES custom_field_definitions(id) ON DELETE CASCADE,
  option_id uuid NOT NULL REFERENCES custom_field_options(id) ON DELETE CASCADE,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_property_custom_field_multi_values UNIQUE (property_id, field_definition_id, option_id)
);

CREATE TABLE pages (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  page_type_id uuid NOT NULL REFERENCES page_types(id) ON DELETE RESTRICT,
  title text NOT NULL,
  slug text NOT NULL,
  content text NOT NULL,
  excerpt text,
  is_published boolean NOT NULL DEFAULT false,
  published_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  deleted_at timestamptz,
  search_vector tsvector,
  CONSTRAINT uq_pages_slug UNIQUE (slug)
);

CREATE TABLE landing_pages (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  page_id uuid NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
  location_id uuid REFERENCES locations(id) ON DELETE CASCADE,
  property_type_id uuid REFERENCES property_types(id) ON DELETE CASCADE,
  deal_type_id uuid REFERENCES deal_types(id) ON DELETE CASCADE,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_landing_pages_page_id UNIQUE (page_id)
);

CREATE UNIQUE INDEX uq_landing_pages_filter_tuple
  ON landing_pages (
    COALESCE(location_id, '00000000-0000-0000-0000-000000000000'::uuid),
    COALESCE(property_type_id, '00000000-0000-0000-0000-000000000000'::uuid),
    COALESCE(deal_type_id, '00000000-0000-0000-0000-000000000000'::uuid)
  );

CREATE TABLE seo_metadata (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  entity_type text NOT NULL CHECK (entity_type IN ('property', 'page', 'blog_post', 'office', 'location', 'landing_page')),
  entity_id uuid NOT NULL,
  title_tag text,
  meta_description text,
  h1 text,
  canonical_url text,
  robots_meta text,
  og_title text,
  og_description text,
  og_image_url text,
  twitter_title text,
  twitter_description text,
  twitter_image_url text,
  schema_json jsonb,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_seo_metadata_entity UNIQUE (entity_type, entity_id)
);

CREATE TABLE site_documents (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  document_key text NOT NULL,
  title text NOT NULL,
  content text NOT NULL,
  content_format text NOT NULL CHECK (content_format IN ('plain_text', 'markdown', 'json', 'xml')),
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_site_documents_key UNIQUE (document_key)
);

CREATE TABLE blog_posts (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  title text NOT NULL,
  slug text NOT NULL,
  excerpt text,
  content text NOT NULL,
  author_name text,
  featured_image_url text,
  is_published boolean NOT NULL DEFAULT false,
  published_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  deleted_at timestamptz,
  search_vector tsvector,
  CONSTRAINT uq_blog_posts_slug UNIQUE (slug)
);

CREATE TABLE blog_categories (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  name text NOT NULL,
  slug text NOT NULL,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_blog_categories_slug UNIQUE (slug)
);

CREATE TABLE blog_tags (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  name text NOT NULL,
  slug text NOT NULL,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW(),
  CONSTRAINT uq_blog_tags_slug UNIQUE (slug)
);

CREATE TABLE blog_post_categories (
  blog_post_id uuid NOT NULL REFERENCES blog_posts(id) ON DELETE CASCADE,
  category_id uuid NOT NULL REFERENCES blog_categories(id) ON DELETE CASCADE,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  PRIMARY KEY (blog_post_id, category_id)
);

CREATE TABLE blog_post_tags (
  blog_post_id uuid NOT NULL REFERENCES blog_posts(id) ON DELETE CASCADE,
  tag_id uuid NOT NULL REFERENCES blog_tags(id) ON DELETE CASCADE,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  PRIMARY KEY (blog_post_id, tag_id)
);

CREATE TABLE faqs (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  page_id uuid NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
  question text NOT NULL,
  answer text NOT NULL,
  sort_order integer NOT NULL DEFAULT 0,
  is_active boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  updated_at timestamptz NOT NULL DEFAULT NOW()
);

CREATE TABLE audit_logs (
  id uuid PRIMARY KEY DEFAULT generate_uuid_v4(),
  user_id uuid REFERENCES admin_users(id) ON DELETE SET NULL,
  entity_type text NOT NULL,
  entity_id uuid NOT NULL,
  action_type text NOT NULL,
  old_value_json jsonb,
  new_value_json jsonb,
  ip_address inet,
  created_at timestamptz NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_locations_parent_id ON locations(parent_id);
CREATE INDEX idx_locations_type_parent ON locations(location_type_id, parent_id);
CREATE INDEX idx_locations_is_active ON locations(is_active);
CREATE INDEX idx_offices_location_id ON offices(location_id);
CREATE INDEX idx_offices_is_active ON offices(is_active);

CREATE INDEX idx_properties_status_id ON properties(status_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_property_type_id ON properties(property_type_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_deal_type_id ON properties(deal_type_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_location_id ON properties(location_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_office_id ON properties(office_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_is_active ON properties(is_active) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_published_at ON properties(published_at DESC) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_price ON properties(price) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_area_total ON properties(area_total) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_feature_flags ON properties(is_featured, is_luxury, is_new_build) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_listing_filters ON properties(is_active, status_id, deal_type_id, property_type_id, published_at DESC) WHERE deleted_at IS NULL;
CREATE INDEX idx_properties_search_vector ON properties USING GIN (search_vector);

CREATE TRIGGER trg_properties_search_vector
BEFORE INSERT OR UPDATE OF title, short_title, description, address_text ON properties
FOR EACH ROW
EXECUTE PROCEDURE set_properties_search_vector();

CREATE INDEX idx_property_media_property_id ON property_media(property_id, sort_order);
CREATE INDEX idx_inquiries_status_id ON inquiries(status_id);
CREATE INDEX idx_inquiries_type_id ON inquiries(inquiry_type_id);
CREATE INDEX idx_inquiries_property_id ON inquiries(property_id);
CREATE INDEX idx_inquiries_office_id ON inquiries(office_id);
CREATE INDEX idx_inquiries_assigned_to_user_id ON inquiries(assigned_to_user_id);
CREATE INDEX idx_inquiries_created_at ON inquiries(created_at DESC);
CREATE INDEX idx_inquiry_logs_inquiry_id ON inquiry_logs(inquiry_id, created_at DESC);

CREATE INDEX idx_custom_field_groups_property_type_id ON custom_field_groups(property_type_id, sort_order);
CREATE INDEX idx_custom_field_definitions_property_type_id ON custom_field_definitions(property_type_id, sort_order);
CREATE INDEX idx_custom_field_definitions_group_id ON custom_field_definitions(group_id, sort_order);
CREATE INDEX idx_custom_field_definitions_filterable ON custom_field_definitions(is_filterable) WHERE is_active = true;
CREATE INDEX idx_custom_field_options_field_definition_id ON custom_field_options(field_definition_id, sort_order);
CREATE INDEX idx_property_custom_field_values_property_id ON property_custom_field_values(property_id);
CREATE INDEX idx_property_custom_field_values_definition_id ON property_custom_field_values(field_definition_id);
CREATE INDEX idx_property_custom_field_values_number ON property_custom_field_values(field_definition_id, value_number) WHERE value_number IS NOT NULL;
CREATE INDEX idx_property_custom_field_values_boolean ON property_custom_field_values(field_definition_id, value_boolean) WHERE value_boolean IS NOT NULL;
CREATE INDEX idx_property_custom_field_values_option ON property_custom_field_values(field_definition_id, value_option_id) WHERE value_option_id IS NOT NULL;
CREATE INDEX idx_property_custom_field_multi_values_property_id ON property_custom_field_multi_values(property_id, field_definition_id);

CREATE INDEX idx_pages_page_type_id ON pages(page_type_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_pages_is_published ON pages(is_published, published_at DESC) WHERE deleted_at IS NULL;
CREATE INDEX idx_pages_search_vector ON pages USING GIN (search_vector);

CREATE TRIGGER trg_pages_search_vector
BEFORE INSERT OR UPDATE OF title, excerpt, content ON pages
FOR EACH ROW
EXECUTE PROCEDURE set_pages_search_vector();

CREATE INDEX idx_landing_pages_location_id ON landing_pages(location_id);
CREATE INDEX idx_landing_pages_property_type_id ON landing_pages(property_type_id);
CREATE INDEX idx_landing_pages_deal_type_id ON landing_pages(deal_type_id);
CREATE INDEX idx_seo_metadata_entity_type ON seo_metadata(entity_type, entity_id);

CREATE INDEX idx_blog_posts_is_published ON blog_posts(is_published, published_at DESC) WHERE deleted_at IS NULL;
CREATE INDEX idx_blog_posts_search_vector ON blog_posts USING GIN (search_vector);

CREATE TRIGGER trg_blog_posts_search_vector
BEFORE INSERT OR UPDATE OF title, excerpt, content ON blog_posts
FOR EACH ROW
EXECUTE PROCEDURE set_blog_posts_search_vector();

CREATE INDEX idx_blog_post_categories_category_id ON blog_post_categories(category_id);
CREATE INDEX idx_blog_post_tags_tag_id ON blog_post_tags(tag_id);
CREATE INDEX idx_faqs_page_id ON faqs(page_id, sort_order);
CREATE INDEX idx_audit_logs_entity ON audit_logs(entity_type, entity_id, created_at DESC);
CREATE INDEX idx_audit_logs_user_id ON audit_logs(user_id, created_at DESC);

CREATE TRIGGER trg_admin_users_set_updated_at BEFORE UPDATE ON admin_users FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_currencies_set_updated_at BEFORE UPDATE ON currencies FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_property_types_set_updated_at BEFORE UPDATE ON property_types FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_deal_types_set_updated_at BEFORE UPDATE ON deal_types FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_property_statuses_set_updated_at BEFORE UPDATE ON property_statuses FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_location_types_set_updated_at BEFORE UPDATE ON location_types FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_media_types_set_updated_at BEFORE UPDATE ON media_types FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_inquiry_types_set_updated_at BEFORE UPDATE ON inquiry_types FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_inquiry_statuses_set_updated_at BEFORE UPDATE ON inquiry_statuses FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_page_types_set_updated_at BEFORE UPDATE ON page_types FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_locations_set_updated_at BEFORE UPDATE ON locations FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_offices_set_updated_at BEFORE UPDATE ON offices FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_properties_set_updated_at BEFORE UPDATE ON properties FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_inquiries_set_updated_at BEFORE UPDATE ON inquiries FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_custom_field_groups_set_updated_at BEFORE UPDATE ON custom_field_groups FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_custom_field_definitions_set_updated_at BEFORE UPDATE ON custom_field_definitions FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_custom_field_options_set_updated_at BEFORE UPDATE ON custom_field_options FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_property_custom_field_values_set_updated_at BEFORE UPDATE ON property_custom_field_values FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_pages_set_updated_at BEFORE UPDATE ON pages FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_landing_pages_set_updated_at BEFORE UPDATE ON landing_pages FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_seo_metadata_set_updated_at BEFORE UPDATE ON seo_metadata FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_site_documents_set_updated_at BEFORE UPDATE ON site_documents FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_blog_posts_set_updated_at BEFORE UPDATE ON blog_posts FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_blog_categories_set_updated_at BEFORE UPDATE ON blog_categories FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_blog_tags_set_updated_at BEFORE UPDATE ON blog_tags FOR EACH ROW EXECUTE PROCEDURE set_updated_at();
CREATE TRIGGER trg_faqs_set_updated_at BEFORE UPDATE ON faqs FOR EACH ROW EXECUTE PROCEDURE set_updated_at();

COMMIT;
