-- 0009_items_unified_simplify.sql
-- After the bidirectional sync triggers (0008), mai.projects is a derived
-- projection of projax.items rather than an independent source. The union
-- form would double-count every mai-managed item, so we collapse the view to
-- a thin projection over projax.items and expose the tags+management columns
-- the store now reads.
--
-- DROP+CREATE rather than CREATE OR REPLACE because Postgres refuses to add
-- columns via the latter even when only appending.

DROP VIEW IF EXISTS projax.items_unified;
CREATE VIEW projax.items_unified AS
SELECT
  i.id,
  i.kind,
  i.title,
  i.slug,
  i.path,
  i.parent_id,
  i.content_md,
  i.aliases,
  i.metadata,
  i.status,
  i.pinned,
  i.archived,
  i.start_time,
  i.end_time,
  'projax'::text AS source,
  (
    SELECT l.ref_id FROM projax.item_links l
    WHERE l.item_id = i.id AND l.ref_type = 'mai-project'
    LIMIT 1
  ) AS source_ref_id,
  i.tags,
  i.management,
  i.created_at,
  i.updated_at
FROM projax.items i
WHERE i.deleted_at IS NULL;

DO $own$ BEGIN
  IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'projax_admin') THEN
    EXECUTE 'ALTER VIEW projax.items_unified OWNER TO projax_admin';
    EXECUTE 'GRANT SELECT ON projax.items_unified TO projax_admin';
  END IF;
END $own$;
