CREATE OR REPLACE VIEW application_view AS

SELECT
    a.id,
    a.status,
    a.submission_date,
    a.comments,
    a.amount_requested,
    a.amount_accepted,
    a.date_accepted,
    a.date_rejected,
    a.is_deleted,
    a.hub_id,
    a.user_id,
    a.evaluation_version AS evaluation_version,
    a.updated_date AS modified_date,
    a.created_date AS created_date,



    -- Call Details
    a.call_id AS call_id,
     cl.name AS call_title,
    cl.end_date AS call_end_date,
    cl.end_time AS call_end_time,

    -- Company Details
    a.COMPANY_ID AS company_id,
    c.company_name AS company_name,

    -- Protocol Details
    p.protocol_number AS protocol_number,


	 -- Assigned User Details from ASSIGNED_APPLICATION and GEPPAFIN_USER
    COALESCE(aa.user_id, NULL) AS assigned_user_id,
    COALESCE(
        NULLIF(
            TRIM(CONCAT(
                COALESCE(u.first_name, ''), ' ',
                COALESCE(u.last_name, '')
            )),
            ''
        ),
        ''
    ) AS assigned_user_name,

-- User with Company Details (From Application's User)
    COALESCE(uwc.id, NULL) AS user_with_company_id


FROM gepafin_schema.APPLICATION a

-- Join Call Entity
LEFT JOIN gepafin_schema.CALL cl
    ON a.CALL_ID = cl.id

-- Join Company Entity (Ensuring it is not deleted)
LEFT JOIN gepafin_schema.COMPANY c
    ON a.COMPANY_ID = c.id

-- Join Protocol Entity
LEFT JOIN gepafin_schema.PROTOCOL p
    ON a.PROTOCOL_NUMBER = p.id

-- Join Assigned Application Entity (Ensuring it is not deleted)
LEFT JOIN gepafin_schema.assigned_applications aa
    ON a.id = aa.APPLICATION_ID
    AND (aa.IS_DELETED IS FALSE OR aa.IS_DELETED IS NULL)

	-- Join User Entity (Get First & Last Name Combined)
LEFT JOIN gepafin_schema.GEPAFIN_USER u
    ON aa.user_id = u.id

    -- Get User With Company ID (From Application's User & Company)
    LEFT JOIN gepafin_schema.USER_WITH_COMPANY uwc
        ON a.user_id = uwc.user_id
        AND a.COMPANY_ID = uwc.company_id
        AND uwc.is_deleted = FALSE -- Ensuring the user is active

WHERE a.IS_DELETED IS FALSE OR a.IS_DELETED IS NULL;