alter table course_product_details
  add column if not exists registered_access text not null default 'paid',
  add column if not exists junior_access text not null default 'paid',
  add column if not exists senior_access text not null default 'paid';

update course_product_details
set
  registered_access = case access_policy
    when 'free_all' then 'free'
    when 'paid_all' then 'paid'
    when 'member_free_guest_paid' then 'paid'
    when 'members_only_free' then 'closed'
    when 'junior_paid_senior_free' then 'closed'
    when 'senior_only_free' then 'closed'
    else registered_access
  end,
  junior_access = case access_policy
    when 'free_all' then 'free'
    when 'paid_all' then 'paid'
    when 'member_free_guest_paid' then 'free'
    when 'members_only_free' then 'free'
    when 'junior_paid_senior_free' then 'paid'
    when 'senior_only_free' then 'closed'
    else junior_access
  end,
  senior_access = case access_policy
    when 'free_all' then 'free'
    when 'paid_all' then 'paid'
    when 'member_free_guest_paid' then 'free'
    when 'members_only_free' then 'free'
    when 'junior_paid_senior_free' then 'free'
    when 'senior_only_free' then 'free'
    else senior_access
  end;

update course_product_details
set
  registered_price_amount = case when registered_access = 'paid' and registered_price_amount = 0 then products.price_amount else registered_price_amount end,
  junior_price_amount = case when junior_access = 'paid' and junior_price_amount = 0 then products.price_amount else junior_price_amount end,
  senior_price_amount = case when senior_access = 'paid' and senior_price_amount = 0 then products.price_amount else senior_price_amount end
from products
where products.id = course_product_details.product_id;

alter table course_product_details
  drop constraint if exists course_product_details_registered_access_check,
  drop constraint if exists course_product_details_junior_access_check,
  drop constraint if exists course_product_details_senior_access_check;

alter table course_product_details
  add constraint course_product_details_registered_access_check check (registered_access in ('closed', 'free', 'paid')),
  add constraint course_product_details_junior_access_check check (junior_access in ('closed', 'free', 'paid')),
  add constraint course_product_details_senior_access_check check (senior_access in ('closed', 'free', 'paid'));
