-- name: CreatePlannedConsignmentDocuments :one
INSERT INTO plannedconsignments_documents(
    document_id,
    document,
    plc_id   
 ) VALUES (
    $1,
    $2,
    $3
  )
  RETURNING *;

 -- name: GetPlannedConsignmentDocuments :one
SELECT * FROM plannedconsignments_documents
WHERE id = $1 LIMIT 1;

-- name: ListPlannedConsigmentsDocuments :many
SELECT * FROM plannedconsignments_documents
ORDER BY id LIMIT $1
OFFSET $2;

-- name: UpdatePlannedConsigmentDocuments :one
UPDATE plannedconsignments_documents
  set 
      document                                    = COALESCE(sqlc.narg(document),document),
      document_id                                 = COALESCE(sqlc.narg(document_id),document_id)
WHERE id = sqlc.arg(id) 
RETURNING *;

-- name: DeletePlannedConsigmentDocument :exec
DELETE FROM plannedconsignments_documents WHERE id= $1;

-- name: GetPlannedConsignmentDocumentsByConsignmentNo :many
SELECT plannedconsignments_documents.document_id,plannedconsignments_documents.id,
plannedconsignments_documents.document,plannedconsignments_documents.plc_id,
documents.name,documents.description,documents.documentusage,documents.iscrop,
documents.isglobal,plannedconsignments_documents.created_at FROM plannedconsignments_documents
JOIN documents on documents.id = plannedconsignments_documents.document_id
WHERE plc_id = $1;


-- name: CheckPlannedConsignmentDocumentsByConsignmentNo :one
SELECT EXISTS(
   SELECT 1 FROM plannedconsignments_documents
   WHERE plc_id = $1
);

-- name: CheckPlannedConsignmentDocumentsByID :one
SELECT EXISTS(
   SELECT 1 FROM plannedconsignments_documents
   WHERE document_id = $1
);



-- name: GetPlannedConsignmentOtherDocumentsByConsignmentNo :many
SELECT * FROM plannedconsignments_otherdocuments
WHERE plannedconsignments_id = $1 LIMIT 1;

-- name: CheckPlannedConsignmentOtherDocumentsByConsignmentNo :one
SELECT EXISTS(
   SELECT 1 FROM plannedconsignments_otherdocuments
   WHERE plannedconsignments_id = $1
);


-- name: CreatePlannedConsignmentQueries :one
INSERT INTO consignment_queries(
    plannedconsignment_id,
    reason,
    user_id
 ) VALUES (
    $1, 
    $2, 
    $3
  )
  RETURNING *;

-- name: DeletePlcDocs :exec
DELETE FROM plannedconsignments_documents WHERE plc_id= $1;

-- name: DeletePlcDocsByID :exec
DELETE FROM plannedconsignments_documents WHERE document_id= $1;

-- name: DeletePlcDocsByRow :exec
DELETE FROM plannedconsignments_documents WHERE id= $1;

-- name: DeleteOtherPlcDocs :exec
DELETE FROM plannedconsignments_otherdocuments WHERE plannedconsignments_id= $1;