-- Drop loose policies
DROP POLICY IF EXISTS "Allow authenticated full access to companies" ON public.companies;
DROP POLICY IF EXISTS "Allow authenticated full access to employees" ON public.employees;

-- Tighten Companies RLS (Only admins or users belonging to the company)
CREATE POLICY "Users can view their own company"
ON public.companies
FOR SELECT TO authenticated
USING (
    id IN (
        SELECT company_id FROM public.employees WHERE user_id = auth.uid()
    )
);

CREATE POLICY "Personal employee record view"
ON public.employees
FOR SELECT TO authenticated
USING (user_id = auth.uid());

CREATE POLICY "Employees can view colleagues in their company"
ON public.employees
FOR SELECT TO authenticated
USING (
    company_id IN (
        SELECT company_id FROM public.employees WHERE user_id = auth.uid()
    )
);

CREATE POLICY "Managers can manage employees in their company"
ON public.employees
FOR ALL TO authenticated
USING (
    company_id IN (
        SELECT company_id FROM public.employees WHERE user_id = auth.uid()
    )
)
WITH CHECK (
    company_id IN (
        SELECT company_id FROM public.employees WHERE user_id = auth.uid()
    )
);
