CREATE VIEW "public"."vendor_candidates_with_vendor_info" AS (select "vendor_candidates"."id", "vendor_candidates"."company_name", "vendor_candidates"."contact_email", "vendor_candidates"."contact_phone", "vendor_candidates"."tax_id", "vendor_candidates"."address", "vendor_candidates"."country", "vendor_candidates"."source", "vendor_candidates"."status", "vendor_candidates"."items", "vendor_candidates"."remark", "vendor_candidates"."created_at", "vendor_candidates"."updated_at", "vendors"."vendor_name", "vendors"."vendor_code", "vendors"."created_at" as "vendor_created_at", (
        SELECT l2."created_at"
          FROM "vendor_candidate_logs" l2
         WHERE l2."vendor_candidate_id" = "vendor_candidates"."id"
           AND l2."action" = 'status_change'
         ORDER BY l2."created_at" DESC
         LIMIT 1
      ) as "last_status_change_at", (
        SELECT u."name"
          FROM "users" u
          JOIN "vendor_candidate_logs" l3
            ON l3."user_id" = u."id"
         WHERE l3."vendor_candidate_id" = "vendor_candidates"."id"
           AND l3."action" = 'status_change'
         ORDER BY l3."created_at" DESC
         LIMIT 1
      ) as "last_status_change_by", (
        SELECT l4."created_at"
          FROM "vendor_candidate_logs" l4
         WHERE l4."vendor_candidate_id" = "vendor_candidates"."id"
           AND l4."action" = 'invite_sent'
         ORDER BY l4."created_at" DESC
         LIMIT 1
      ) as "last_invitation_at", (
        SELECT u2."name"
          FROM "users" u2
          JOIN "vendor_candidate_logs" l5
            ON l5."user_id" = u2."id"
         WHERE l5."vendor_candidate_id" = "vendor_candidates"."id"
           AND l5."action" = 'invite_sent'
         ORDER BY l5."created_at" DESC
         LIMIT 1
      ) as "last_invitation_by" from "vendor_candidates" left join "vendors" on "vendor_candidates"."vendor_id" = "vendors"."id");