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

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

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

        [HttpGet("{JobListingID}")]
        public async Task<IActionResult> GetJobListing([FromRoute] int JobListingID) {
            var jobListing = await _databaseService.GetJobListing(JobListingID);
            if (jobListing != null) {
                return Ok(jobListing);
            }
            return NotFound("Job listing not found");
        }

        [HttpGet("company")]
        public async Task<IActionResult> GetCompanysJobListings([FromQuery] int CompanyID) {
            if (isLoggedIn()) {
                if (await isLoggedInUserEmployeeOf(CompanyID)) {
                    JobListing[] jobListings = await _databaseService.GetJobListingFromCompany(CompanyID);
                    return Ok(jobListings);
                }
                return NotFound("You are not an employee of company");
            }
            return NotFound("Not logged in");
        }

        [HttpGet]
        public async Task<IActionResult> GetJobListings(int Page = 1, int PageQuantity = 25) {
            JobListing[] jobListings = await _databaseService.GetJobListingPage(Page, PageQuantity);
            return Ok(jobListings);
        }

        [HttpPost]
        public async Task<IActionResult> SetJobListing([FromBody] JobListing JobListing) {
            if (isLoggedIn()) {
                if (await isLoggedInUserEmployeeOf(JobListing.CompanyID)) {
                    await _databaseService.SetJobListing(JobListing);
                    return Ok();
                }
                return NotFound("You are not an employee of company");
            }
            return NotFound("Not logged in");
        }

        [HttpDelete]
        public async Task<IActionResult> DeleteJobListing(int JobListingID) {
            if (isLoggedIn()) {
                JobListing? jobListing = await _databaseService.GetJobListing(JobListingID);
                if (jobListing != null) {
                    if (await isLoggedInUserEmployeeOf(JobListingID)) {
                        await _databaseService.DeleteJobListing(JobListingID);
                        return Ok();
                    }
                    return NotFound("You are not an employee of company");
                }
                return NotFound("Job listing doesn't exist already");
            }
            return NotFound("Not logged in");
        }

    }

}
