-- name: migration-0000-create-files#
CREATE TABLE IF NOT EXISTS files (
   id INTEGER PRIMARY KEY AUTOINCREMENT
 , user_id INTEGER
 , filename TEXT
 , path TEXT
 , upload_date TEXT
 , FOREIGN KEY(user_id) REFERENCES user(id)
);

-- name: migration-0004-create-file-analysis#
CREATE TABLE IF NOT EXISTS file_analysis (
   id INTEGER PRIMARY KEY AUTOINCREMENT
 , max_x INTEGER
 , max_y INTEGER
 , max_z INTEGER
 , max_end INTEGER
 , max_bed INTEGER
 , nozzle_diameter FLOAT
 , filament_id INTEGER REFERENCES filament(id)
 , file_id INTEGER REFERENCES file(id)
);

-- name: create-file^
INSERT INTO files (
   user_id
 , filename
 , path
 , upload_date
)
VALUES (:uid, :filename, :path , datetime('now'))
RETURNING
   id
;

-- name: list-files
SELECT
   *
 , (SELECT COUNT(*) FROM jobs WHERE file_id = f.id AND status_id > 1) AS `print_successes`
 , (SELECT COUNT(*) FROM jobs WHERE file_id = f.id AND status_id < 0) AS `print_failures`
FROM files f
WHERE
   (:uid IS NULL OR user_id = :uid)
;

-- name: delete-file!
DELETE FROM files
WHERE
   user_id = :uid
   AND id = :fid
;

-- name: delete-file-analysis-by-fid!
DELETE FROM file_analysis
WHERE
   file_id = :fid
;

-- name: delete-file-analysis!
DELETE FROM file_analysis
WHERE
   id = :aid
;

-- name: fetch-file^
SELECT
   *
FROM files
WHERE
   (:uid IS NULL OR user_id = :uid)
   AND id = :fid
;

-- name: create-analysis^
INSERT INTO file_analysis (
   max_x
 , max_y
 , max_z
 , max_end
 , max_bed
 , nozzle_diameter
 , filament_id
 , file_id
)
VALUES (
   :max_x
 , :max_y
 , :max_z
 , :max_end
 , :max_bed
 , :nozzle
 , :filament_id
 , :file_id
)
RETURNING
  id
;

-- name: list-unanalyzed-files
SELECT
   f.id
 , f.path
 , f.filename
 , f.user_id
FROM files f
LEFT JOIN file_analysis fa
   ON f.id = fa.file_id
WHERE
   fa.file_id IS NULL
;
