using Microsoft.AspNetCore.Mvc;
using BoredCareers.Services.DatabaseService;
using BoredCareers.Entities;
using System.Web.Http;

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

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

        [HttpGet]
        public async Task<IActionResult> GetCompany(int CompanyID) {
            if (isLoggedIn()) {
                Company? company = await _databaseService.GetCompany(CompanyID);
                if (company != null) {
                    return Ok(company);
                }
                return NotFound("Company doesn't exist");
            }
            return NotFound("Not logged in");
        }

        [HttpPost]
        public async Task<IActionResult> SetCompany([FromBody] Company company, [FromQuery] bool newCompany = false) {
            if (isLoggedIn()) {
                if (newCompany) {
                    Company? test = await _databaseService.GetCompany(company.ID);
                    if (test == null) {
                        company.ID = await _databaseService.SetCompany(company);
                        await _databaseService.SetEmployee(new Employee() {
                            AccountID = getLoggedInUserID(),
                            Company = company
                        });
                        return Ok();
                    }
                    return NotFound("The company already exists");
                } else {
                    if (await isLoggedInUserEmployeeOf(company.ID)) {
                        await _databaseService.SetCompany(company);
                        return Ok();
                    }
                    return NotFound("You are not an employee of company");
                }
            }
            return NotFound("Not logged in");
        }

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

    }

}
