use std::collections::HashMap;

use crate::{
    database::{Database, Error, Result},
    entities::{Client, Company, Invoice, Job, Tag, Worker},
    jobber::JobberGet,
};

impl JobberGet for Database {
    fn get_company(&self) -> Result<&Company> {
        if let Some(company) = &self.company {
            Ok(company)
        } else {
            Err(Error::NoCompany)
        }
    }

    fn get_worker(&self, id: &str) -> Result<&Worker> {
        if let Some(worker) = self.workers.get(id) {
            Ok(worker)
        } else {
            Err(Error::WorkerNotFound(id.to_string()))
        }
    }

    fn get_client(&self, id: &str) -> Result<&Client> {
        if let Some(client) = self.clients.get(id) {
            Ok(client)
        } else {
            Err(Error::ClientNotFound(id.to_string()))
        }
    }

    fn get_job(&self, id: usize) -> Result<&Job> {
        if id >= self.jobs.len() {
            return Err(Error::JobNotFound(id));
        }
        Ok(&self.jobs[id])
    }

    fn get_tag(&self, name: &str) -> Result<&Tag> {
        if let Some(tag) = self.tags.get(name) {
            Ok(tag)
        } else {
            Err(Error::TagNotFound(name.to_string()))
        }
    }

    fn get_tags(&self) -> &HashMap<String, Tag> {
        &self.tags
    }

    fn get_invoice(&self, id: usize) -> Result<&Invoice> {
        if id >= self.invoices.len() {
            return Err(Error::InvoiceNotFound(id));
        }
        Ok(&self.invoices[id])
    }
}
