using Microsoft.AspNetCore.Mvc;
using BoredCareers.Services.DatabaseService;
using BoredCareers.Entities;

namespace BoredCareers.Controllers {
    [ApiController]
    [Route("api/application")]
    public class ApplicationController : MistoxControllerBase {

        public ApplicationController(DatabaseService db) : base(db) {}

        [HttpGet]
        public async Task<IActionResult> GetApplication(int? ApplicationID, int? JobListingID) {
            if (isLoggedIn()) {
                if (ApplicationID != null) {
                    Application? application = await _databaseService.GetApplication(Convert.ToInt32(ApplicationID));
                    if (application != null) {
                        return Ok(application);
                    }
                    return NotFound("Application doesn't exist");
                } else if (JobListingID != null) {
                    Application[] applications = await _databaseService.GetApplicationsFromJobListing(Convert.ToInt32(JobListingID));
                    return Ok(applications);
                }
                return NotFound("No query selector supplied");
            }
            return NotFound("Not logged in");
        }

        [HttpPost]
        public async Task<IActionResult> SetApplication([FromBody] Application application) {
            if (isLoggedIn()) {
                if (application.AccountID == getLoggedInUserID()) {
                    await _databaseService.SetApplication(application);
                    return Ok();
                }
                return NotFound("Cannot apply for someone else");
            }
            return NotFound("Not logged in");
        }

        [HttpDelete]
        public async Task<IActionResult> DeleteApplication(int ApplicationID) {
            if (isLoggedIn()) {
                Application? app = await _databaseService.GetApplication(ApplicationID);
                if (app != null) {
                    if (app.AccountID == getLoggedInUserID()) {
                        await _databaseService.DeleteApplication(ApplicationID);
                        return Ok();
                    }
                    return NotFound("You cannot delete an app that isnt yours");
                }
                return NotFound("Application doesn't exist");
            }
            return NotFound("Not logged in");
        }

    }

}
