import UserService from "../services/UserService";
import Controller from "./Controller";

export default class UploadController extends Controller {
	public async Index_Post_AllowAnonymous() {
		const data = await this.req.file();
		if (data && data.type === "file") {
			let uploadKey: string = "";
			let host: string = "";
			//console.log(this.req.headers);
			if ("upload-key" in this.req.headers) {
				// @ts-ignore
				uploadKey = this.req.headers["upload-key"];
			} else {
				return this.unauthorised("Upload key invalid or missing.");
			}
			if ("host" in this.req.headers) {
				// @ts-ignore
				host = this.req.headers["host"];
			} else {
				return this.badRequest("Host header missing?!");
			}

			const user = await UserService.GetByUploadKey(uploadKey);
			if (!user) {
				return this.unauthorised("Upload key invalid or missing.");
			}

			const fileUrl = await UserService.UploadMedia(user.Id, host, data);
			if (!fileUrl) {
				return this.badRequest("This domain is not registered to your EUS account.");
			}

			return this.ok(fileUrl);
		}

		return this.badRequest();
	}
}