//@ts-check
import core from '@actions/core'
import github from '@actions/github'
import os from 'os'
import fs from 'fs'
import mime from 'mime'
import path from 'path'

try {
    const file = core.getInput('file')
    if (!file) {
        core.setFailed('"file" is required')
    }
    const token = core.getInput('token')
    if (!token) {
        core.setFailed('"token" is required')
    }

    const machine_name = core.getInput('custom-machine-name') || os.hostname()
    const custom_name = core.getInput('custom-name') || path.basename(file)
    const mime_type = core.getInput('content-type') || mime.getType(file) || 'data/raw'
    const use_salt = core.getInput('use-salt') === 'true'
    
    console.log("Uploading file: ", file)
    console.log("Name: ", custom_name)
    console.log("Machine name: ", machine_name)
    console.log("Content type: ", mime_type)
    console.log("Use salt: ", use_salt)

    const fileContent = fs.readFileSync(file)

    await fetch('https://lgoaduploader.rphsw.workers.dev/', 
        { 
            method: 'POST',
            body: fileContent,
            headers: {
                'Content-Type': mime_type,
                'x-machine-name': machine_name,
                'x-custom-name': custom_name,
                'x-salt-name': use_salt ? 'true' : 'false',
                'authorization': `Bearer ${token}`
            }
        }).then(response => { return response.text() })
        .then(uri => {
            console.log("Uploaded to: ", uri)
            core.setOutput('uri', uri)
            const url = "https://free.estrogen.download/" + uri
            console.log("Usable URL: ", url)
            core.setOutput('url', url)
        }).then(() => {
            console.log("Done!")
        })
} catch (err) {
    core.setFailed(err.message)
}