-- name: get-user-by-email^
SELECT u.id,
       u.username,
       u.email,
       u.salt,
       u.hashed_password,
       u.bio,
        u.image,
        u.phone,
        u.user_type,
        u.company_name,
       u.created_at,
       u.updated_at,
       COALESCE(array_agg(DISTINCT r.name) FILTER (WHERE r.name IS NOT NULL), '{}') AS roles
FROM users u
LEFT JOIN user_roles ur ON ur.user_id = u.id
LEFT JOIN roles r ON r.id = ur.role_id
WHERE u.email = :email
GROUP BY u.id
LIMIT 1;


-- name: get-user-by-username^
SELECT u.id,
       u.username,
       u.email,
       u.salt,
       u.hashed_password,
       u.bio,
        u.image,
        u.phone,
        u.user_type,
        u.company_name,
       u.created_at,
       u.updated_at,
       COALESCE(array_agg(DISTINCT r.name) FILTER (WHERE r.name IS NOT NULL), '{}') AS roles
FROM users u
LEFT JOIN user_roles ur ON ur.user_id = u.id
LEFT JOIN roles r ON r.id = ur.role_id
WHERE u.username = :username
GROUP BY u.id
LIMIT 1;


-- name: create-new-user<!
INSERT INTO users (username, email, salt, hashed_password)
VALUES (:username, :email, :salt, :hashed_password)
RETURNING
    id, created_at, updated_at;


-- name: update-user-by-username<!
UPDATE
    users
SET username        = :new_username,
    email           = :new_email,
    salt            = :new_salt,
    hashed_password = :new_password,
    bio             = :new_bio,
    image           = :new_image,
    phone           = :new_phone,
    user_type       = :new_user_type,
    company_name    = :new_company_name
WHERE username = :username
RETURNING
    updated_at;


-- name: get-user-by-id^
SELECT u.id,
       u.username,
       u.email,
       u.salt,
       u.hashed_password,
       u.bio,
        u.image,
        u.phone,
        u.user_type,
        u.company_name,
       u.created_at,
       u.updated_at,
       COALESCE(array_agg(DISTINCT r.name) FILTER (WHERE r.name IS NOT NULL), '{}') AS roles
FROM users u
LEFT JOIN user_roles ur ON ur.user_id = u.id
LEFT JOIN roles r ON r.id = ur.role_id
WHERE u.id = :id
GROUP BY u.id
LIMIT 1;


-- name: admin-update-user-by-id^
UPDATE users
SET username        = COALESCE(:new_username, username),
    email           = COALESCE(:new_email, email),
    salt            = COALESCE(:new_salt, salt),
    hashed_password = COALESCE(:new_password, hashed_password),
    bio             = COALESCE(:new_bio, bio),
    image           = COALESCE(:new_image, image),
    phone           = COALESCE(:new_phone, phone),
    user_type       = COALESCE(:new_user_type, user_type),
    company_name    = COALESCE(:new_company_name, company_name)
WHERE id = :id
RETURNING id,
          username,
          email,
          salt,
          hashed_password,
          bio,
          image,
          phone,
          user_type,
          company_name,
          created_at,
          updated_at;


-- name: admin-delete-user!
DELETE FROM users
WHERE id = :id;
