DROP VIEW "public"."document_stages_view";--> statement-breakpoint
CREATE VIEW "public"."document_stages_view" AS (
  SELECT
    d.id AS document_id,
    d.doc_number,
    d.title,
    d.status,
    d.issued_date,
    d.contract_id,

    (
      SELECT COUNT(*)
      FROM issue_stages
      WHERE document_id = d.id
    ) AS stage_count,

    COALESCE( 
      (
        SELECT json_agg(i.stage_name)
        FROM issue_stages i
        WHERE i.document_id = d.id
      ), 
      '[]'
    ) AS stage_list,

    d.created_at,
    d.updated_at
  FROM documents d
);