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

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

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

        [HttpGet("{CompanyID}")]
        public async Task<IActionResult> GetEmployees([FromRoute] int CompanyID) {
            if (isLoggedIn()) {
                if (await isLoggedInUserEmployeeOf(CompanyID)) { 
                    Employee[] employees = await _databaseService.GetEmployeesFromCompany(CompanyID);
                    foreach (Employee cur in employees) {
                        cur.Company.EmailToken = "";
                    }
                    return Ok(employees);
                }
                return NotFound("You are not an employee of company");
            }
            return NotFound("Not logged in");
        }

        [HttpGet]
        public async Task<IActionResult> GetEmployee() {
            if (isLoggedIn()) {
                Employee[] employees = await _databaseService.GetEmployeeOfCompanyByAccountID(getLoggedInUserID());
                foreach (Employee cur in employees) {
                    cur.Company.EmailToken = "";
                }
                return Ok(employees);
            }
            return NotFound("Not logged in");
        }

        [HttpPost]
        public async Task<IActionResult> SetEmployee([FromBody] Employee employee) {
            if (isLoggedIn()) {
                if (await isLoggedInUserEmployeeOf(Convert.ToInt32(employee.Company.ID))) {
                    await _databaseService.SetEmployee(employee);
                    return Ok();
                }
                return NotFound("You are not an employee of company");
            }
            return NotFound("Not logged in");
        }

        [HttpDelete]
        public async Task<IActionResult> DeleteEmployee(int EmployeeID) {
            if (isLoggedIn()) {
                Employee? employee = await _databaseService.GetEmployee(EmployeeID);
                if (employee != null) {
                    if (await isLoggedInUserEmployeeOf(Convert.ToInt32(employee.Company.ID))) {
                        await _databaseService.DeleteEmployee(EmployeeID);
                        return Ok();
                    }
                    return NotFound("You are not an employee of company");
                }
                return NotFound("Employee not found");
            }
            return NotFound("Not logged in");
        }

    }

}
