BEGIN;

INSERT INTO admin_users (email, full_name, role_code, password_hash)
VALUES ('admin@example.com', 'Системен администратор', 'super_admin', 'replace-me')
ON CONFLICT (email) DO NOTHING;

WITH country AS (
  INSERT INTO locations (location_type_id, country_code, name, slug, is_active)
  SELECT id, 'GR', 'Гърция', 'greece', true
  FROM location_types
  WHERE code = 'country'
  ON CONFLICT DO NOTHING
  RETURNING id
), country_resolved AS (
  SELECT id FROM country
  UNION ALL
  SELECT id FROM locations WHERE slug = 'greece'
  LIMIT 1
), region AS (
  INSERT INTO locations (parent_id, location_type_id, country_code, name, slug, latitude, longitude, is_active)
  SELECT country_resolved.id, lt.id, 'GR', 'Атика', 'attica', 37.983810, 23.727539, true
  FROM country_resolved
  CROSS JOIN location_types lt
  WHERE lt.code = 'region'
  ON CONFLICT DO NOTHING
  RETURNING id
), region_resolved AS (
  SELECT id FROM region
  UNION ALL
  SELECT l.id
  FROM locations l
  JOIN locations p ON p.id = l.parent_id
  WHERE l.slug = 'attica' AND p.slug = 'greece'
  LIMIT 1
), city AS (
  INSERT INTO locations (parent_id, location_type_id, country_code, name, slug, latitude, longitude, is_active)
  SELECT region_resolved.id, lt.id, 'GR', 'Атина', 'athens', 37.983810, 23.727539, true
  FROM region_resolved
  CROSS JOIN location_types lt
  WHERE lt.code = 'city'
  ON CONFLICT DO NOTHING
  RETURNING id
), city_resolved AS (
  SELECT id FROM city
  UNION ALL
  SELECT l.id
  FROM locations l
  JOIN locations p ON p.id = l.parent_id
  WHERE l.slug = 'athens' AND p.slug = 'attica'
  LIMIT 1
)
INSERT INTO offices (location_id, name, slug, email, phone, address, city, region, latitude, longitude, working_hours, is_active)
SELECT
  city_resolved.id,
  'ElladaHomes Athens Office',
  'elladahomes-athens-office',
  'athens.office@example.com',
  '+30 210 123 4567',
  'Vasilissis Sofias 10',
  'Атина',
  'Атика',
  37.983810,
  23.727539,
  'Понеделник - Петък, 09:00 - 18:00',
  true
FROM city_resolved
ON CONFLICT (slug) DO NOTHING;

INSERT INTO pages (page_type_id, title, slug, content, excerpt, is_published, published_at)
SELECT
  pt.id,
  'Често задавани въпроси',
  'faq',
  'Базова FAQ страница за демо среда.',
  'Демо FAQ страница',
  true,
  NOW()
FROM page_types pt
WHERE pt.code = 'faq'
ON CONFLICT (slug) DO NOTHING;

INSERT INTO blog_categories (name, slug)
VALUES
  ('Инвестиции', 'investments'),
  ('Региони', 'regions')
ON CONFLICT (slug) DO NOTHING;

INSERT INTO blog_tags (name, slug)
VALUES
  ('Golden Visa', 'golden-visa'),
  ('Пазар', 'market')
ON CONFLICT (slug) DO NOTHING;

INSERT INTO blog_posts (title, slug, excerpt, content, author_name, featured_image_url, is_published, published_at)
VALUES (
  '5 причини да инвестирате в имот в Гърция',
  '5-reasons-invest-greece',
  'Кратък демо материал за пазарните предимства на Гърция.',
  'Подробно демо съдържание за инвестиции в гръцки недвижими имоти.',
  'Редакционен екип',
  'https://images.unsplash.com/photo-1555993539-1732b0258235?w=1200',
  true,
  NOW()
)
ON CONFLICT (slug) DO NOTHING;

INSERT INTO blog_post_categories (blog_post_id, category_id)
SELECT bp.id, bc.id
FROM blog_posts bp
JOIN blog_categories bc ON bc.slug = 'investments'
WHERE bp.slug = '5-reasons-invest-greece'
ON CONFLICT DO NOTHING;

INSERT INTO blog_post_tags (blog_post_id, tag_id)
SELECT bp.id, bt.id
FROM blog_posts bp
JOIN blog_tags bt ON bt.slug IN ('golden-visa', 'market')
WHERE bp.slug = '5-reasons-invest-greece'
ON CONFLICT DO NOTHING;

WITH office_resolved AS (
  SELECT id FROM offices WHERE slug = 'elladahomes-athens-office'
), city_resolved AS (
  SELECT id FROM locations WHERE slug = 'athens' LIMIT 1
)
INSERT INTO properties (
  ref_number,
  slug,
  title,
  short_title,
  description,
  property_type_id,
  deal_type_id,
  status_id,
  office_id,
  location_id,
  price,
  currency_code,
  area_total,
  area_built,
  bedrooms_count,
  bathrooms_count,
  floor_number,
  floors_total,
  year_built,
  latitude,
  longitude,
  address_text,
  is_featured,
  is_new_build,
  is_luxury,
  is_active,
  published_at
)
SELECT
  'GR-DEMO-0001',
  'luxury-sea-view-apartment-athens',
  'Луксозен апартамент с морска гледка в Атина',
  'Луксозен апартамент в Атина',
  'Демо обява за висок клас апартамент в Атина с гледка, паркомясто и висок стандарт на довършване.',
  pt.id,
  dt.id,
  ps.id,
  office_resolved.id,
  city_resolved.id,
  385000.00,
  'EUR',
  125.00,
  118.00,
  3,
  2,
  4,
  6,
  2024,
  37.866000,
  23.753400,
  'Glyfada, Athens',
  true,
  true,
  true,
  true,
  NOW()
FROM property_types pt
CROSS JOIN deal_types dt
CROSS JOIN property_statuses ps
CROSS JOIN office_resolved
CROSS JOIN city_resolved
WHERE pt.code = 'apartment'
  AND dt.code = 'sale'
  AND ps.code = 'active'
ON CONFLICT (ref_number) DO NOTHING;

INSERT INTO property_media (property_id, media_type_id, file_url, alt_text, title, sort_order, is_cover)
SELECT
  p.id,
  mt.id,
  'https://images.unsplash.com/photo-1502672260266-1c1ef2d93688?w=1200',
  'Луксозен апартамент в Атина',
  'Основна снимка',
  1,
  true
FROM properties p
JOIN media_types mt ON mt.code = 'image'
WHERE p.ref_number = 'GR-DEMO-0001'
ON CONFLICT DO NOTHING;

INSERT INTO custom_field_groups (property_type_id, name, code, sort_order, is_active)
SELECT pt.id, 'Основни характеристики', 'main_features', 10, true
FROM property_types pt
WHERE pt.code = 'apartment'
ON CONFLICT (property_type_id, code) DO NOTHING;

INSERT INTO custom_field_definitions (
  property_type_id,
  group_id,
  code,
  label,
  field_type,
  placeholder,
  help_text,
  is_required,
  is_filterable,
  is_visible_in_listing,
  is_visible_in_detail,
  sort_order,
  is_active
)
SELECT
  pt.id,
  cfg.id,
  'sea_view',
  'Морска гледка',
  'boolean',
  NULL,
  'Показва дали имотът има морска гледка.',
  false,
  true,
  true,
  true,
  10,
  true
FROM property_types pt
JOIN custom_field_groups cfg ON cfg.property_type_id = pt.id AND cfg.code = 'main_features'
WHERE pt.code = 'apartment'
ON CONFLICT (property_type_id, code) DO NOTHING;

INSERT INTO property_custom_field_values (
  property_id,
  field_definition_id,
  value_boolean
)
SELECT
  p.id,
  cfd.id,
  true
FROM properties p
JOIN custom_field_definitions cfd ON cfd.code = 'sea_view'
WHERE p.ref_number = 'GR-DEMO-0001'
ON CONFLICT (property_id, field_definition_id) DO NOTHING;

INSERT INTO seo_metadata (
  entity_type,
  entity_id,
  title_tag,
  meta_description,
  h1,
  canonical_url,
  robots_meta,
  og_title,
  og_description
)
SELECT
  'property',
  p.id,
  'Луксозен апартамент с морска гледка в Атина',
  'SEO демо описание за апартамент в Атина.',
  'Луксозен апартамент с морска гледка в Атина',
  'https://example.com/properties/luxury-sea-view-apartment-athens',
  'index,follow',
  'Луксозен апартамент в Атина',
  'Демо Open Graph описание за апартамент в Атина.'
FROM properties p
WHERE p.ref_number = 'GR-DEMO-0001'
ON CONFLICT (entity_type, entity_id) DO NOTHING;

INSERT INTO inquiries (
  inquiry_type_id,
  property_id,
  office_id,
  full_name,
  email,
  phone,
  message,
  source,
  source_url,
  status_id,
  assigned_to_user_id,
  ip_address
)
SELECT
  it.id,
  p.id,
  o.id,
  'Мария Иванова',
  'maria@example.com',
  '+359888123456',
  'Интересувам се от демо апартамента в Атина.',
  'website',
  'https://example.com/properties/luxury-sea-view-apartment-athens',
  ist.id,
  au.id,
  '127.0.0.1'
FROM inquiry_types it
JOIN inquiry_statuses ist ON ist.code = 'new'
JOIN properties p ON p.ref_number = 'GR-DEMO-0001'
JOIN offices o ON o.id = p.office_id
JOIN admin_users au ON au.email = 'admin@example.com'
WHERE it.code = 'property'
  AND NOT EXISTS (
    SELECT 1
    FROM inquiries i
    WHERE i.inquiry_type_id = it.id
      AND i.property_id = p.id
      AND i.email = 'maria@example.com'
  );

INSERT INTO faqs (page_id, question, answer, sort_order, is_active)
SELECT
  p.id,
  'Могат ли чужденци да купуват имот в Гърция?',
  'Да, чужденци могат да купуват имоти в Гърция при спазване на местната правна рамка.',
  10,
  true
FROM pages p
WHERE p.slug = 'faq'
  AND NOT EXISTS (
    SELECT 1
    FROM faqs f
    WHERE f.page_id = p.id
      AND f.question = 'Могат ли чужденци да купуват имот в Гърция?'
  );

INSERT INTO site_documents (document_key, title, content, content_format, is_active)
VALUES (
  'llms_txt',
  'llms.txt',
  'User-agent: *' || E'\n' || 'Allow: /' || E'\n' || 'Preferred-language: bg',
  'plain_text',
  true
)
ON CONFLICT (document_key) DO NOTHING;

INSERT INTO audit_logs (user_id, entity_type, entity_id, action_type, new_value_json, ip_address)
SELECT
  au.id,
  'property',
  p.id,
  'create',
  jsonb_build_object('ref_number', p.ref_number, 'title', p.title),
  '127.0.0.1'
FROM admin_users au
JOIN properties p ON p.ref_number = 'GR-DEMO-0001'
WHERE au.email = 'admin@example.com'
  AND NOT EXISTS (
    SELECT 1
    FROM audit_logs al
    WHERE al.entity_type = 'property'
      AND al.entity_id = p.id
      AND al.action_type = 'create'
  );

COMMIT;
